[英]Python Pandas : How to add new calculated column to the next of specific column in the existing dataframe?
I created a 'new' column in the dataframe.我在数据框中创建了一个“新”列。 Now I want to add this 'new' column between columns B and C. Please suggest how to do it.现在我想在 B 列和 C 列之间添加这个“新”列。请建议如何做。
df = pd.DataFrame({'A':[10,0,200,50,500],'B': [50,200,70,90,800],'C':[100,500,60,300,70]})
df['new'] = ((df['C'] - df['B'])/df['B']) * 100
you can use pandas.DataFrame.iloc
to arrange your columns您可以使用pandas.DataFrame.iloc
来排列您的列
>>> df = df.iloc[:, [0,1,3,2]] # After new column
>>> df
A B new C
0 10 50 100.000000 100
1 0 200 150.000000 500
2 200 70 -14.285714 60
3 50 90 233.333333 300
4 500 800 -91.250000 70
This is DataFrame.insert
.这是DataFrame.insert
。 Though really the condition would be after column B.虽然实际上条件是在 B 列之后。
#df = pd.DataFrame({'A': [10, 0, 200, 50, 500],
# 'B': [50, 200, 70, 90, 800],
# 'C': [100, 500, 60, 300, 70]})
df.insert(loc=df.columns.get_loc('B')+1, # After column 'B'
column='new', # named `'new'`
value=(df['C'] - df['B'])/df['B']*100)
print(df)
A B new C
0 10 50 100.000000 100
1 0 200 150.000000 500
2 200 70 -14.285714 60
3 50 90 233.333333 300
4 500 800 -91.250000 70
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.