Get the name of a pandas DataFrame

前端 未结 5 455
灰色年华
灰色年华 2020-11-27 06:48

How do I get the name of a DataFrame and print it as a string?

Example:

boston (var name assigned to a csv file)

import pandas         


        
相关标签:
5条回答
  • 2020-11-27 06:48

    From here what I understand DataFrames are:

    DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table, or a dict of Series objects.

    And Series are:

    Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.).

    Series have a name attribute which can be accessed like so:

     In [27]: s = pd.Series(np.random.randn(5), name='something')
    
     In [28]: s
     Out[28]: 
     0    0.541
     1   -1.175
     2    0.129
     3    0.043
     4   -0.429
     Name: something, dtype: float64
    
     In [29]: s.name
     Out[29]: 'something'
    

    EDIT: Based on OP's comments, I think OP was looking for something like:

     >>> df = pd.DataFrame(...)
     >>> df.name = 'df' # making a custom attribute that DataFrame doesn't intrinsically have
     >>> print(df.name)
     'df'
    
    0 讨论(0)
  • 2020-11-27 06:52

    Sometimes df.name doesn't work.

    you might get an error message:

    'DataFrame' object has no attribute 'name'

    try the below function:

    def get_df_name(df):
        name =[x for x in globals() if globals()[x] is df][0]
        return name
    
    0 讨论(0)
  • 2020-11-27 06:53

    Here is a sample function: 'df.name = file` : Sixth line in the code below

    def df_list(): filename_list = current_stage_files(PATH) df_list = [] for file in filename_list: df = pd.read_csv(PATH+file) df.name = file df_list.append(df) return df_list

    0 讨论(0)
  • 2020-11-27 06:59

    In many situations, a custom attribute attached to a pd.DataFrame object is not necessary. In addition, note that pandas-object attributes may not serialize. So pickling will lose this data.

    Instead, consider creating a dictionary with appropriately named keys and access the dataframe via dfs['some_label'].

    df = pd.DataFrame()
    
    dfs = {'some_label': df}
    
    0 讨论(0)
  • 2020-11-27 07:08

    You can name the dataframe with the following, and then call the name wherever you like:

    import pandas as pd
    df = pd.DataFrame( data=np.ones([4,4]) )
    df.name = 'Ones'
    
    print df.name
    >>>
    Ones
    

    Hope that helps.

    0 讨论(0)
提交回复
热议问题