如何对由元组组成的数据帧中的第二个值求和,并使用输出在数据帧中创建新列

时间:2019-07-02 13:05:23

标签: python pandas dataframe functional-programming tuples

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

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

Stand-Alone model

1 个答案:

答案 0 :(得分:0)

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

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)。结果是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)