简体   繁体   English

对数据框熊猫的列中存在的列表执行计算

[英]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.

相关问题 如何对pandas dataframe中列的子集进行计算? - How to perform calculations on a subset of a column in a pandas dataframe? Pandas DataFrame:如何删除列并对选择的列执行计算 - Pandas DataFrame: How to remove column and perform calculations on select columns 如何检查 dataframe pandas 中是否不存在列列表 - how to check if a list of column in not present in a dataframe pandas 根据索引值对数据框列执行计算 - Perform calculations on dataframe column based on index value 根据列值对 dataframe 的子集进行计算 - Perform calculations on subset of dataframe based on column value 对 pandas DataFrame 列的计算以另一列为条件 - Calculations on a pandas DataFrame column conditional on another column 根据列列表中的值对Pandas Dataframe进行切片 - Slicing Pandas Dataframe based on a value present in a column which is a list of lists 写一个function对一个Pandas中的多列进行计算 dataframe - Write a function to perform calculations on multiple columns in a Pandas dataframe 用一个查询跨pandas数据框的两列执行数学计算? - perform math calculations across two columns in pandas dataframe with one query? 如果熊猫数据框列中存在列表值列表,请用另一个熊猫列中的值替换它们 - If list of lists values are present in Pandas dataframe column replace them with values from another Pandas column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM