我在用熊猫阅读的csv中有数据。数据具有这种格式-
name company income saving
A AA 100 10
B AA 200 20
我希望创建一个新行,名称为A,公司AA,收入和储蓄为A和B的差额。
预期输出-
name company income saving
A AA -100 -10
答案 0 :(得分:0)
我认为需要:
print (df)
name company income saving
0 A AA 100 10
1 B AA 200 20
2 C AA 300 40
#for select columns by names
df1 = df[['name','company']].join(df[['income','saving']].diff(-1))
#for select columns by positions
#df1 = df.iloc[:, :2].join(df.iloc[:, 2:].diff(-1))
print (df1)
name company income saving
0 A AA -100.0 -10.0
1 B AA -100.0 -20.0
2 C AA NaN NaN