[英]Pandas create df that is the product of columns in another df
我有以下熊貓數據框:
id | a | b | c | d
------------------
0 | 1 | 3 | 4 | 5
1 | 2 | 3 | 5 | 6
我想創建一個新的df,其列是第一個df中連續列的差
新df:
id | b-a | c-b | d-c
--------------------
0 | 2 | 1 | 1
1 | 1 | 2 | 1
謝謝
您可以將sub
與shift
一起使用,以刪除第一列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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.