Naming a column in pandas that is dependent on a function

Viewed 70

Suppose I have a pandas dataframe, df.

a = len(series) - 6
df['M20'] = ...

It is irrelevant to show what the dataset series looks like, but len(series) = 26, so a = 20.

Is there a way of writing something like df['Ma'] instead of df['M20']?

I am running a monthly process, meaning next month len(series) would equal 27, a would equal 21, and so I don't want to have to manually change all of the 20s to 21s etc.

1 Answers

Use format:

a = len(series) - 6
df['M{}'.format(a)] = ...

df['M{}'.format(len(series) - 6)] = ...

Or f-strings for python 3.6+:

df[f'M{a}'] = ...

df[f'M{len(series) - 6}'] = ...
Related