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 as pd boston = pd.read_csv('boston.csv') print('The winner is team A based on the %s table.) % boston
To access the names of a Pandas dataframe, we can the method columns(). For example, if our dataframe is called df we just type print(df. columns) to get all the columns of the Pandas dataframe. After this, we can work with the columns to access certain columns, rename a column, and so on.
You can get column names in Pandas dataframe using df. columns statement. Usecase: This is useful when you want to show all columns in a dataframe in the output console (E.g. in the jupyter notebook console).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With