[英]Perform calculations on a list present in a column of a dataframe pandas
I have the below dataframe: 我有以下数据框:
Position A B
0 29644164 71.0 [31, 38, 1, 1]
1 45861974 45.0 [17, 26, 1, 1]
2 58142396 69.0 [37, 31, 0, 1]
3 41223046 75.0 [21, 53, 0, 1]
I'd like to do calculations on column B. I'd like to sum the 2 numbers in 2 last positions, and divide them with the sum of all 4 numbers. 我想对B列进行计算。我想将2个数字加到最后2个位置,然后将它们除以所有4个数字的和。 Then, add the results to a new column 'calc'
然后,将结果添加到新列“ calc”中
So the dataframe I'm expecting will be: 因此,我期望的数据帧将是:
Position A B calc
0 29644164 71.0 [3, 5, 1, 1] 0.2
1 45861974 45.0 [2, 2, 1, 1] 0.333
2 58142396 69.0 [3, 7, 0, 1] 0.1
3 41223046 75.0 [3, 2, 0, 1] 0.2
How can I do it? 我该怎么做?
Use list comprehension: 使用清单理解:
df['calc'] = [sum(x[-2:]) / sum(x) for x in df.B]
print (df)
Position A B calc
0 29644164 71.0 [31, 38, 1, 1] 0.028169
1 45861974 45.0 [17, 26, 1, 1] 0.044444
2 58142396 69.0 [37, 31, 0, 1] 0.014493
3 41223046 75.0 [21, 53, 0, 1] 0.013333
Details : 详细资料 :
print ([sum(x[-2:]) for x in df.B])
[2, 2, 1, 1]
print ([sum(x) for x in df.B])
[71, 45, 69, 75]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.