Skip to content Skip to sidebar Skip to footer

Dynamically Adding Columns To Pandas Dataframe

I have a pandas dataframe with column names 'a', 'b', ...,'n'. for each column I want to show the daily change for the columns and extend the dataframe to consist of: 'a','b',...,'

Solution 1:

Use the variable name not a string:

for column_name indf:
    df[column_name + '_daily'] = df[column_name].pct_change(freq=1).fillna(0)

Names are import. Use the singular form: column_name.

Solution 2:

You need to pass the column name only not as a string:

for column_names indf:
    df[str(column_names) + '_daily'] = df[column_names].pct_change(freq=1).fillna(0)

Also I think you don't need to cast the column name back to str again:

for column_names indf:
    df[column_names + '_daily'] = df[column_names].pct_change(freq=1).fillna(0)

should work.

So the error gets raised because df['column_names'] doesn't exist, the iterable are the column names so passing this as the key will just work

Post a Comment for "Dynamically Adding Columns To Pandas Dataframe"