简体   繁体   中英

Add Pandas dataframe name as a column in dataframe

I would like to add the name of my dataframe as a column in my dataframe.

I'm trying:

DF_NAME = pd.read_csv('CSV_LOCATION', encoding = "ISO-8859-1")
DF_NAME['NAME'] = DF_NAME.NAME

Any pointers appreciated, thanks.

If you have multiple dataframes and that causes the issue, consider using dict instead of variables and it will make it much easier to achieve your goal.

Example:

my_frames = {}

my_frames['DF_NAME'] = pd.read_csv('CSV_LOCATION', encoding = "ISO-8859-1")

for k, v in my_frames.items():
    my_frames[k] = v.assign(Name = k)

A DataFrame object doesn't have an attribute called NAME. So, you have to create it first, using DF_NAME.NAME = 'MyDF' or DF_NAME['NAME'] = 'MyDF' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM