![](/img/trans.png)
[英]Pandas multiply the value in one column with another if the column vaues are numbers?
[英]How to divide/multiply value of a column with value of another column in pandas?
我的數據框看起來很喜歡
Minutes Played, Points, Assists
MP PTS TRB AST FG% BLK 3P%
0 2810 793 678 117 0.485 74 0.315
1 263 101 30 19 0.402 7 0.385
2 4241 1170 1178 144 0.548 201 0.000
我想將這些數據框轉換為具有這些列的數據框
Points/Minutes, Assists/Minutes
基本上第一列是播放的總分鍾數,我希望將所有剩余的統計信息隱瞞為每分鍾。
是的,我在做
input_data['PTS']/input_data['MP']
然后將所有系列串聯起來,這樣做的pythonic方法是什么? 如何使用Map / lambda操作做到這一點?
您可以使用IIUC:
print input_data
MP PTS TRB AST FG% BLK 3P%
0 2810 793 678 117 0.485 74 0.315
1 263 101 30 19 0.402 7 0.385
2 4241 1170 1178 144 0.548 201 0.000
input_data['A'] = input_data['PTS']/input_data['MP']
input_data['B'] = input_data['AST']/input_data['MP']
print input_data
MP PTS TRB AST FG% BLK 3P% A B
0 2810 793 678 117 0.485 74 0.315 0.282206 0.041637
1 263 101 30 19 0.402 7 0.385 0.384030 0.072243
2 4241 1170 1178 144 0.548 201 0.000 0.275878 0.033954
print pd.DataFrame({'A': input_data['A'],'B': input_data['B']}, index=input_data.index)
A B
0 0.282206 0.041637
1 0.384030 0.072243
2 0.275878 0.033954
用第一列除數據框以外的所有列。
df.iloc[:, ].apply(lambda s: s / df.iloc[:, 0])
PTS TRB AST FG% BLK 3P%
0 0.282206 0.241281 0.041637 0.000173 0.026335 0.000112
1 0.384030 0.114068 0.072243 0.001529 0.026616 0.001464
2 0.275878 0.277765 0.033954 0.000129 0.047394 0.000000
這也適用:
df.iloc[:, 1:].div(df.iloc[:, 0].values, axis=0)
我相信您隨后將需要重新計算FG%和3P%列。 這將對原始數據幀進行分割,而MP,FG%和3P%保持不變。
df.iloc[:, [1, 2, 3, 5]] = df.iloc[:, [1, 2, 3, 5]].div(df.iloc[:, 0].values, axis=0)
>>> df
MP PTS TRB AST FG% BLK 3P%
0 2810 0.282206 0.241281 0.041637 0.485 0.026335 0.315
1 263 0.384030 0.114068 0.072243 0.402 0.026616 0.385
2 4241 0.275878 0.277765 0.033954 0.548 0.047394 0.000
ps勇士!!!
不,串聯新系列是很慣用的。
您還可以使用df['newcol'] = ...
來構建所需的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.