Pandas创建df,它是另一个df中列的乘积

时间:2017-03-23 09:06:57

标签: python pandas dataframe

我有以下pandas数据帧:

id | a | b | c | d
------------------
 0 | 1 | 3 | 4 | 5
 1 | 2 | 3 | 5 | 6

我想创建一个新的df,其列是第一个df中连续列的差异

new df:

id | b-a | c-b | d-c
--------------------
 0 |  2  |  1  |  1 
 1 |  1  |  2  |  1

谢谢

1 个答案:

答案 0 :(得分:3)

您可以将subshift一起使用,以删除第一列iloc

df = df.set_index('id')
df = df.sub(df.shift(axis=1)).iloc[:, 1:].reset_index()
print (df)
   id    b    c    d
0   0  2.0  1.0  1.0
1   1  1.0  2.0  1.0

如果需要转换为int

df = df.set_index('id')
df = df.sub(df.shift(axis=1)).iloc[:, 1:].astype(int).reset_index()
print (df)
   id  b  c  d
0   0  2  1  1
1   1  1  2  1

对于更改的列名:

df = df.set_index('id')
cols = df.columns

df = df.sub(df.shift(axis=1)).iloc[:, 1:].astype(int)
df.columns = cols[1:] + '-' + cols[:-1]
df = df.reset_index()
print (df)
   id  b-a  c-b  d-c
0   0    2    1    1
1   1    1    2    1
相关问题