Analyst
Analyst

Reputation: 139

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.

Upvotes: 1

Views: 189

Answers (2)

zipa
zipa

Reputation: 27869

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)

Upvotes: 1

Subhtrance
Subhtrance

Reputation: 11

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'.

Upvotes: 1

Related Questions