How to store Dataframe data to Firebase Storage?












4















Given a pandas Dataframe which contains some data, what is the best to store this data to Firebase?



Should I convert the Dataframe to a local file (e.g. .csv, .txt) and then upload it on Firebase Storage, or is it also possible to directly store the pandas Dataframe without conversion? Or are there better best practices?



Update 01/03 - So far I've come with this solution, which requires writing a csv file locally, then reading it in and uploading it and then deleting the local file. I doubt however that this is the most efficient method, thus I would like to know if it can be done better and quicker?



import os
import firebase_admin
from firebase_admin import db, storage

cred = firebase_admin.credentials.Certificate(cert_json)
app = firebase_admin.initialize_app(cred, config)
bucket = storage.bucket(app=app)

def upload_df(df, data_id):
"""
Upload a Dataframe as a csv to Firebase Storage
:return: storage_ref
"""

# Storage location + extension
storage_ref = data_id + ".csv"

# Store locally
df.to_csv(data_id)

# Upload to Firebase Storage
blob = bucket.blob(storage_ref)
with open(data_id,'rb') as local_file:
blob.upload_from_file(local_file)

# Delete locally
os.remove(data_id)

return storage_ref









share|improve this question

























  • Do you want to query it or just store the file? If you want to perform queries on the data then you need to obey the Firebase database data types.

    – b-fg
    Dec 21 '18 at 14:47











  • No query just to retrieve the data again as a dataframe

    – JohnAndrews
    Dec 21 '18 at 15:04











  • Have tried using this pypi.org/project/python-firebase. I think you have to write a custom script.

    – Umer
    Jan 2 at 10:29











  • I don't think firebase is appropriate for a tabular data structure but the best way I can think of is to use to_json method of the DataFrame with orient='records' and save each row as a document. If it's a small table you can also use orient='table' which stores meta data (data types etc.) as well.

    – ayhan
    Jan 2 at 15:45
















4















Given a pandas Dataframe which contains some data, what is the best to store this data to Firebase?



Should I convert the Dataframe to a local file (e.g. .csv, .txt) and then upload it on Firebase Storage, or is it also possible to directly store the pandas Dataframe without conversion? Or are there better best practices?



Update 01/03 - So far I've come with this solution, which requires writing a csv file locally, then reading it in and uploading it and then deleting the local file. I doubt however that this is the most efficient method, thus I would like to know if it can be done better and quicker?



import os
import firebase_admin
from firebase_admin import db, storage

cred = firebase_admin.credentials.Certificate(cert_json)
app = firebase_admin.initialize_app(cred, config)
bucket = storage.bucket(app=app)

def upload_df(df, data_id):
"""
Upload a Dataframe as a csv to Firebase Storage
:return: storage_ref
"""

# Storage location + extension
storage_ref = data_id + ".csv"

# Store locally
df.to_csv(data_id)

# Upload to Firebase Storage
blob = bucket.blob(storage_ref)
with open(data_id,'rb') as local_file:
blob.upload_from_file(local_file)

# Delete locally
os.remove(data_id)

return storage_ref









share|improve this question

























  • Do you want to query it or just store the file? If you want to perform queries on the data then you need to obey the Firebase database data types.

    – b-fg
    Dec 21 '18 at 14:47











  • No query just to retrieve the data again as a dataframe

    – JohnAndrews
    Dec 21 '18 at 15:04











  • Have tried using this pypi.org/project/python-firebase. I think you have to write a custom script.

    – Umer
    Jan 2 at 10:29











  • I don't think firebase is appropriate for a tabular data structure but the best way I can think of is to use to_json method of the DataFrame with orient='records' and save each row as a document. If it's a small table you can also use orient='table' which stores meta data (data types etc.) as well.

    – ayhan
    Jan 2 at 15:45














4












4








4








Given a pandas Dataframe which contains some data, what is the best to store this data to Firebase?



Should I convert the Dataframe to a local file (e.g. .csv, .txt) and then upload it on Firebase Storage, or is it also possible to directly store the pandas Dataframe without conversion? Or are there better best practices?



Update 01/03 - So far I've come with this solution, which requires writing a csv file locally, then reading it in and uploading it and then deleting the local file. I doubt however that this is the most efficient method, thus I would like to know if it can be done better and quicker?



import os
import firebase_admin
from firebase_admin import db, storage

cred = firebase_admin.credentials.Certificate(cert_json)
app = firebase_admin.initialize_app(cred, config)
bucket = storage.bucket(app=app)

def upload_df(df, data_id):
"""
Upload a Dataframe as a csv to Firebase Storage
:return: storage_ref
"""

# Storage location + extension
storage_ref = data_id + ".csv"

# Store locally
df.to_csv(data_id)

# Upload to Firebase Storage
blob = bucket.blob(storage_ref)
with open(data_id,'rb') as local_file:
blob.upload_from_file(local_file)

# Delete locally
os.remove(data_id)

return storage_ref









share|improve this question
















Given a pandas Dataframe which contains some data, what is the best to store this data to Firebase?



Should I convert the Dataframe to a local file (e.g. .csv, .txt) and then upload it on Firebase Storage, or is it also possible to directly store the pandas Dataframe without conversion? Or are there better best practices?



Update 01/03 - So far I've come with this solution, which requires writing a csv file locally, then reading it in and uploading it and then deleting the local file. I doubt however that this is the most efficient method, thus I would like to know if it can be done better and quicker?



import os
import firebase_admin
from firebase_admin import db, storage

cred = firebase_admin.credentials.Certificate(cert_json)
app = firebase_admin.initialize_app(cred, config)
bucket = storage.bucket(app=app)

def upload_df(df, data_id):
"""
Upload a Dataframe as a csv to Firebase Storage
:return: storage_ref
"""

# Storage location + extension
storage_ref = data_id + ".csv"

# Store locally
df.to_csv(data_id)

# Upload to Firebase Storage
blob = bucket.blob(storage_ref)
with open(data_id,'rb') as local_file:
blob.upload_from_file(local_file)

# Delete locally
os.remove(data_id)

return storage_ref






python pandas firebase dataframe






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 3 at 8:53







JohnAndrews

















asked Dec 21 '18 at 14:32









JohnAndrewsJohnAndrews

1,65133481




1,65133481













  • Do you want to query it or just store the file? If you want to perform queries on the data then you need to obey the Firebase database data types.

    – b-fg
    Dec 21 '18 at 14:47











  • No query just to retrieve the data again as a dataframe

    – JohnAndrews
    Dec 21 '18 at 15:04











  • Have tried using this pypi.org/project/python-firebase. I think you have to write a custom script.

    – Umer
    Jan 2 at 10:29











  • I don't think firebase is appropriate for a tabular data structure but the best way I can think of is to use to_json method of the DataFrame with orient='records' and save each row as a document. If it's a small table you can also use orient='table' which stores meta data (data types etc.) as well.

    – ayhan
    Jan 2 at 15:45



















  • Do you want to query it or just store the file? If you want to perform queries on the data then you need to obey the Firebase database data types.

    – b-fg
    Dec 21 '18 at 14:47











  • No query just to retrieve the data again as a dataframe

    – JohnAndrews
    Dec 21 '18 at 15:04











  • Have tried using this pypi.org/project/python-firebase. I think you have to write a custom script.

    – Umer
    Jan 2 at 10:29











  • I don't think firebase is appropriate for a tabular data structure but the best way I can think of is to use to_json method of the DataFrame with orient='records' and save each row as a document. If it's a small table you can also use orient='table' which stores meta data (data types etc.) as well.

    – ayhan
    Jan 2 at 15:45

















Do you want to query it or just store the file? If you want to perform queries on the data then you need to obey the Firebase database data types.

– b-fg
Dec 21 '18 at 14:47





Do you want to query it or just store the file? If you want to perform queries on the data then you need to obey the Firebase database data types.

– b-fg
Dec 21 '18 at 14:47













No query just to retrieve the data again as a dataframe

– JohnAndrews
Dec 21 '18 at 15:04





No query just to retrieve the data again as a dataframe

– JohnAndrews
Dec 21 '18 at 15:04













Have tried using this pypi.org/project/python-firebase. I think you have to write a custom script.

– Umer
Jan 2 at 10:29





Have tried using this pypi.org/project/python-firebase. I think you have to write a custom script.

– Umer
Jan 2 at 10:29













I don't think firebase is appropriate for a tabular data structure but the best way I can think of is to use to_json method of the DataFrame with orient='records' and save each row as a document. If it's a small table you can also use orient='table' which stores meta data (data types etc.) as well.

– ayhan
Jan 2 at 15:45





I don't think firebase is appropriate for a tabular data structure but the best way I can think of is to use to_json method of the DataFrame with orient='records' and save each row as a document. If it's a small table you can also use orient='table' which stores meta data (data types etc.) as well.

– ayhan
Jan 2 at 15:45












2 Answers
2






active

oldest

votes


















1














if you just want to reduce code length and the steps of creating and deleting files, you can use upload_from_string:



import firebase_admin
from firebase_admin import db, storage

cred = firebase_admin.credentials.Certificate(cert_json)
app = firebase_admin.initialize_app(cred, config)
bucket = storage.bucket(app=app)

def upload_df(df, data_id):
"""
Upload a Dataframe as a csv to Firebase Storage
:return: storage_ref
"""
storage_ref = data_id + '.csv'
blob = bucket.blob(storage_ref)
blob.upload_from_string(df.to_csv())

return storage_ref


https://googleapis.github.io/google-cloud-python/latest/storage/blobs.html#google.cloud.storage.blob.Blob.upload_from_string






share|improve this answer































    3





    +25









    With python-firebase and to_dict:



    postdata = my_df.to_dict()

    # Assumes any auth/headers you need are already taken care of.
    result = firebase.post('/my_endpoint', postdata, {'print': 'pretty'})
    print(result)
    # Snapshot info


    You can get the data back using the snapshot info and endpoint, and reestablish the df with from_dict(). You could adapt this solution to SQL and JSON solutions, which pandas also has support for.



    Alternatively and depending on where you script executes from, you might consider treating firebase as a db and using the dbapi from firebase_admin (check this out.)



    As for whether it's according to best practice, it's difficult to say without knowing anything about your use case.






    share|improve this answer
























    • You assume its better to store it to Firebase instead of Firebase Storage?

      – JohnAndrews
      Jan 2 at 15:38











    • You mean firebase db vs firebase storage? Again that's more specific to your use case

      – Charles Landau
      Jan 2 at 15:40











    • My question relates to Firebase Storage not the DB as in your answer.

      – JohnAndrews
      Jan 3 at 8:55






    • 2





      My answer was for firebase storage AND suggested a firebase DB alternative

      – Charles Landau
      Jan 3 at 16:41











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53886485%2fhow-to-store-dataframe-data-to-firebase-storage%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    if you just want to reduce code length and the steps of creating and deleting files, you can use upload_from_string:



    import firebase_admin
    from firebase_admin import db, storage

    cred = firebase_admin.credentials.Certificate(cert_json)
    app = firebase_admin.initialize_app(cred, config)
    bucket = storage.bucket(app=app)

    def upload_df(df, data_id):
    """
    Upload a Dataframe as a csv to Firebase Storage
    :return: storage_ref
    """
    storage_ref = data_id + '.csv'
    blob = bucket.blob(storage_ref)
    blob.upload_from_string(df.to_csv())

    return storage_ref


    https://googleapis.github.io/google-cloud-python/latest/storage/blobs.html#google.cloud.storage.blob.Blob.upload_from_string






    share|improve this answer




























      1














      if you just want to reduce code length and the steps of creating and deleting files, you can use upload_from_string:



      import firebase_admin
      from firebase_admin import db, storage

      cred = firebase_admin.credentials.Certificate(cert_json)
      app = firebase_admin.initialize_app(cred, config)
      bucket = storage.bucket(app=app)

      def upload_df(df, data_id):
      """
      Upload a Dataframe as a csv to Firebase Storage
      :return: storage_ref
      """
      storage_ref = data_id + '.csv'
      blob = bucket.blob(storage_ref)
      blob.upload_from_string(df.to_csv())

      return storage_ref


      https://googleapis.github.io/google-cloud-python/latest/storage/blobs.html#google.cloud.storage.blob.Blob.upload_from_string






      share|improve this answer


























        1












        1








        1







        if you just want to reduce code length and the steps of creating and deleting files, you can use upload_from_string:



        import firebase_admin
        from firebase_admin import db, storage

        cred = firebase_admin.credentials.Certificate(cert_json)
        app = firebase_admin.initialize_app(cred, config)
        bucket = storage.bucket(app=app)

        def upload_df(df, data_id):
        """
        Upload a Dataframe as a csv to Firebase Storage
        :return: storage_ref
        """
        storage_ref = data_id + '.csv'
        blob = bucket.blob(storage_ref)
        blob.upload_from_string(df.to_csv())

        return storage_ref


        https://googleapis.github.io/google-cloud-python/latest/storage/blobs.html#google.cloud.storage.blob.Blob.upload_from_string






        share|improve this answer













        if you just want to reduce code length and the steps of creating and deleting files, you can use upload_from_string:



        import firebase_admin
        from firebase_admin import db, storage

        cred = firebase_admin.credentials.Certificate(cert_json)
        app = firebase_admin.initialize_app(cred, config)
        bucket = storage.bucket(app=app)

        def upload_df(df, data_id):
        """
        Upload a Dataframe as a csv to Firebase Storage
        :return: storage_ref
        """
        storage_ref = data_id + '.csv'
        blob = bucket.blob(storage_ref)
        blob.upload_from_string(df.to_csv())

        return storage_ref


        https://googleapis.github.io/google-cloud-python/latest/storage/blobs.html#google.cloud.storage.blob.Blob.upload_from_string







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 3 at 17:19









        fcsrfcsr

        623413




        623413

























            3





            +25









            With python-firebase and to_dict:



            postdata = my_df.to_dict()

            # Assumes any auth/headers you need are already taken care of.
            result = firebase.post('/my_endpoint', postdata, {'print': 'pretty'})
            print(result)
            # Snapshot info


            You can get the data back using the snapshot info and endpoint, and reestablish the df with from_dict(). You could adapt this solution to SQL and JSON solutions, which pandas also has support for.



            Alternatively and depending on where you script executes from, you might consider treating firebase as a db and using the dbapi from firebase_admin (check this out.)



            As for whether it's according to best practice, it's difficult to say without knowing anything about your use case.






            share|improve this answer
























            • You assume its better to store it to Firebase instead of Firebase Storage?

              – JohnAndrews
              Jan 2 at 15:38











            • You mean firebase db vs firebase storage? Again that's more specific to your use case

              – Charles Landau
              Jan 2 at 15:40











            • My question relates to Firebase Storage not the DB as in your answer.

              – JohnAndrews
              Jan 3 at 8:55






            • 2





              My answer was for firebase storage AND suggested a firebase DB alternative

              – Charles Landau
              Jan 3 at 16:41
















            3





            +25









            With python-firebase and to_dict:



            postdata = my_df.to_dict()

            # Assumes any auth/headers you need are already taken care of.
            result = firebase.post('/my_endpoint', postdata, {'print': 'pretty'})
            print(result)
            # Snapshot info


            You can get the data back using the snapshot info and endpoint, and reestablish the df with from_dict(). You could adapt this solution to SQL and JSON solutions, which pandas also has support for.



            Alternatively and depending on where you script executes from, you might consider treating firebase as a db and using the dbapi from firebase_admin (check this out.)



            As for whether it's according to best practice, it's difficult to say without knowing anything about your use case.






            share|improve this answer
























            • You assume its better to store it to Firebase instead of Firebase Storage?

              – JohnAndrews
              Jan 2 at 15:38











            • You mean firebase db vs firebase storage? Again that's more specific to your use case

              – Charles Landau
              Jan 2 at 15:40











            • My question relates to Firebase Storage not the DB as in your answer.

              – JohnAndrews
              Jan 3 at 8:55






            • 2





              My answer was for firebase storage AND suggested a firebase DB alternative

              – Charles Landau
              Jan 3 at 16:41














            3





            +25







            3





            +25



            3




            +25





            With python-firebase and to_dict:



            postdata = my_df.to_dict()

            # Assumes any auth/headers you need are already taken care of.
            result = firebase.post('/my_endpoint', postdata, {'print': 'pretty'})
            print(result)
            # Snapshot info


            You can get the data back using the snapshot info and endpoint, and reestablish the df with from_dict(). You could adapt this solution to SQL and JSON solutions, which pandas also has support for.



            Alternatively and depending on where you script executes from, you might consider treating firebase as a db and using the dbapi from firebase_admin (check this out.)



            As for whether it's according to best practice, it's difficult to say without knowing anything about your use case.






            share|improve this answer













            With python-firebase and to_dict:



            postdata = my_df.to_dict()

            # Assumes any auth/headers you need are already taken care of.
            result = firebase.post('/my_endpoint', postdata, {'print': 'pretty'})
            print(result)
            # Snapshot info


            You can get the data back using the snapshot info and endpoint, and reestablish the df with from_dict(). You could adapt this solution to SQL and JSON solutions, which pandas also has support for.



            Alternatively and depending on where you script executes from, you might consider treating firebase as a db and using the dbapi from firebase_admin (check this out.)



            As for whether it's according to best practice, it's difficult to say without knowing anything about your use case.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jan 2 at 14:37









            Charles LandauCharles Landau

            2,7431317




            2,7431317













            • You assume its better to store it to Firebase instead of Firebase Storage?

              – JohnAndrews
              Jan 2 at 15:38











            • You mean firebase db vs firebase storage? Again that's more specific to your use case

              – Charles Landau
              Jan 2 at 15:40











            • My question relates to Firebase Storage not the DB as in your answer.

              – JohnAndrews
              Jan 3 at 8:55






            • 2





              My answer was for firebase storage AND suggested a firebase DB alternative

              – Charles Landau
              Jan 3 at 16:41



















            • You assume its better to store it to Firebase instead of Firebase Storage?

              – JohnAndrews
              Jan 2 at 15:38











            • You mean firebase db vs firebase storage? Again that's more specific to your use case

              – Charles Landau
              Jan 2 at 15:40











            • My question relates to Firebase Storage not the DB as in your answer.

              – JohnAndrews
              Jan 3 at 8:55






            • 2





              My answer was for firebase storage AND suggested a firebase DB alternative

              – Charles Landau
              Jan 3 at 16:41

















            You assume its better to store it to Firebase instead of Firebase Storage?

            – JohnAndrews
            Jan 2 at 15:38





            You assume its better to store it to Firebase instead of Firebase Storage?

            – JohnAndrews
            Jan 2 at 15:38













            You mean firebase db vs firebase storage? Again that's more specific to your use case

            – Charles Landau
            Jan 2 at 15:40





            You mean firebase db vs firebase storage? Again that's more specific to your use case

            – Charles Landau
            Jan 2 at 15:40













            My question relates to Firebase Storage not the DB as in your answer.

            – JohnAndrews
            Jan 3 at 8:55





            My question relates to Firebase Storage not the DB as in your answer.

            – JohnAndrews
            Jan 3 at 8:55




            2




            2





            My answer was for firebase storage AND suggested a firebase DB alternative

            – Charles Landau
            Jan 3 at 16:41





            My answer was for firebase storage AND suggested a firebase DB alternative

            – Charles Landau
            Jan 3 at 16:41


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53886485%2fhow-to-store-dataframe-data-to-firebase-storage%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Mossoró

            Error while reading .h5 file using the rhdf5 package in R

            Pushsharp Apns notification error: 'InvalidToken'