scott martin
scott martin

Reputation: 1293

Pandas - Dynamically passing variable to a column name

I am trying to have one of the columns in the Dataframe to be assigned value of a variable.

For example:

I have a column called : Count of sales done in the past 10 days

I am trying to have the value of 10 in the column name changed dynamically from another variable called date

So each time I update the Dataframe I want the value assigned to the variable date be shown in the column name

For example if date = 4, column name should be Count of sales done in the past 4 days and so on.

I tried to pass df.columns = date but get a KeyError

Upvotes: 1

Views: 744

Answers (1)

jezrael
jezrael

Reputation: 862481

One idea with position of column is use rename:

df = pd.DataFrame({
        'A':list('abcdef'),
         'Count of sales done in the past 10 days':[4,5,4,5,5,4],
         'C':[7,8,9,4,2,3],
})

date = 4
pos = 1

df = df.rename(columns={df.columns[pos]: f'Count of sales done in the past {date} days'})
print (df)
   A  Count of sales done in the past 4 days  C
0  a                                       4  7
1  b                                       5  8
2  c                                       4  9
3  d                                       5  4
4  e                                       5  2
5  f                                       4  3

Another idea is get column by mask and set new values by Index.where, but if mask return more columns names it rewrite all of them:

m = df.columns.str.startswith('Count of sales done in the past')
df.columns = df.columns.where(~m, f'Count of sales done in the past {date} days')

Upvotes: 2

Related Questions