基于循环变量和附加字符串创建新的列名 [英] Creating a new column name based on a loop variable and an additional string
问题描述
我想为数据框中每个浮动的列创建百分比变化列,并使用初始列的名称和添加的"_change"每次将其存储在newn列中
I want to create percentage change column for each column that is a float in my dataframe and stored it in a newn column each time with the name of the initial column and the add on "_change"
我尝试过这个,但是似乎没有任何作用吗?
I tried this but it does not seem to work any idea?
for col in df.columns:
if df[col].dtypes == "float":
df[ col&'_change'] = (df.col - df.groupby(['New_ID']).col.shift(1))/ df.col
例如,如果我的列是df ["Expenses"],我想将百分比变化保存在df ["Expenses_change"]中 编辑以添加示例数据框和输出
for example if my column is df["Expenses"] I would like to save the percentage change in df["Expenses_change"] Edited for adding example data frame and output
df
Index ID Reporting_Date Sales_Am Exp_Am
0 1 01/01/2016 1000 900
1 1 02/01/2016 1050 950
2 1 03/01/2016 1060 960
3 2 01/01/2016 2000 1850
4 2 02/01/2016 2500 2350
4 2 03/01/2016 3000 2850
循环后
Index ID Reporting_Date Sales_Am Sales_Am_chge Exp_Am Exp_Am_chge
0 1 01/01/2016 1000 Null 900 Null
1 1 02/01/2016 1050 5% 950 6%
2 1 03/01/2016 1060 1% 960 1%
3 2 01/01/2016 2000 Null 1850 Null
4 2 02/01/2016 2500 25% 2350 27%
4 2 03/01/2016 3000 20% 2850 21%
请记住,我的数据框上有两列以上.
keep in mind that i have more than 2 columns on my dataframe.
推荐答案
为什么要使用'&'而不是
Why are you using '&' instead of '+' in
df[ col&'_change']
?
这篇关于基于循环变量和附加字符串创建新的列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!