首页 > 解决方案 > 如何对由元组组成的数据框中的第二个值求和并使用输出在数据框中创建一个新列

问题描述

我有一个 6 列和 3 行的数据框。数据框由元组组成,例如(3, 5)(4, 5)(3, 5)(5, 5)(2, 3)(5, 3)

我需要创建一个函数,该函数添加以行中相同的第一个数字开头的第二个元组数,例如(3, 5)将对应(3,5)然后我们添加两个五个,这给我们 10 并将总数保存到同一数据帧中的一个新列中。

这就是我的数据框的样子

标签: pythonpandasdataframefunctional-programmingtuples

解决方案


如果您只想过滤第一个元素的某些值。你可以这样做:

import pandas as pd

df= pd.DataFrame({
        'tuple1': [(3,1), (4,3), (2,2), (3,1)], 
        'tuple2': [(4,1), (1,1), (2,1), (5,2)],
        'tuple3': [(1,2), (2,3), (3,4), (2,5)],
        'tuple4': [(3,4), (1,3), (2,2), (3,1)],
        'tuple5': [(4,2), (1,2), (3,1), (5,4)],
        })

def sum_tuples(df, tup_columns, sum_column, filter_value):
    df[sum_column]= 0
    for col in tup_columns:
        df[sum_column]+= df[col].map(lambda t: t[1] if t[0] == filter_value else 0)

sum_tuples(df, ['tuple1', 'tuple2', 'tuple3', 'tuple4', 'tuple5'], 'sum_threes', 3)

它检查作为列表 (tuple1, ...) 传递的列中的所有元组,并将具有特定值(示例中为 3)的所有第二分量相加,并将结果存储在帧的指定结果列中(sum_threes in这个例子)。结果是 5、0、5、2。

如果您想根据它们的第一个值对所有元组求和,而不必多次调用该函数,则可以按如下方式进行:

# define a function that handles the tuples of a row
# and outputs the sum for all tuples whose first component 
# occured more than once
def agg_tuples(tuples):
    d= dict()
    multiple= set()
    for k, v in tuples:
        if k in d:
            # the first component already occured before
            # for this row --> memorize this in multiple
            d[k]+= v
            multiple.add(k)
        else:
            # value k occured the first time
            d[k]= v
    # now only return the sums of the tuples that occured multiple times
    return [(k, d[k]) for k in multiple]

# prepare an auxillary series with all tuple columns in one list
lists= df.apply(lambda r: agg_tuples([r[col] for col in ['tuple1', 'tuple2', 'tuple3', 'tuple4', 'tuple5']]), axis='columns')

# the following line would be the number of colums we 
# need at least to store all the result tuples
mx= max(lists.map(len))
# now we just need to split the list into seperate columns
# therefore we define three columns
result_cols= ['res1', 'res2', 'res3']
for idx, col in enumerate(result_cols):
    df[col]= lists.map(lambda l: l[idx] if idx<len(l) else None)

推荐阅读