将两个数据帧与一些常见列合并,其中共同需要的组合是自定义函数

问题描述 投票:3回答:1

我的问题与Merge pandas dataframe, with column operation非常相似,但它无法满足我的需求。

假设我有两个数据帧,例如(请注意,数据帧内容可能是浮点数而不是布尔值):

left = pd.DataFrame({0: [True, True, False], 0.5: [False, True, True]}, index=[12.5, 14, 15.5])
right = pd.DataFrame({0.7: [True, False, False], 0.5: [True, False, True]}, index=[12.5, 14, 15.5])

right

        0.5    0.7
12.5   True   True
14.0  False  False
15.5   True  False

left

        0.0    0.5
12.5   True  False
14.0   True   True
15.5  False   True

如您所见,它们具有相同的索引,其中一列是常见的。在现实生活中,可能会有更常见的列,例如1.0处的其他列或尚未定义的其他数字,以及每侧更多的唯一列。我需要组合两个数据帧,以便保留所有唯一列,并使用特定函数组合公共列,例如此示例的布尔值为OR,而两个数据帧的索引始终相同。

所以结果应该是:

result

        0.0   0.5    0.7
12.5   True  True   True
14.0   True  True  False
15.5  False  True  False

在现实生活中,将需要组合两个以上的数据帧,但是它们可以一个接一个地顺序组合到空的第一个数据帧。

我觉得pandas.combine可能会做到这一点,但我无法从文档中弄清楚。任何人都会建议如何在一个或多个步骤中执行此操作。

python pandas merge concat
1个回答
2
投票

您可以连接数据帧,然后按列名称分组以对类似命名的列应用操作:在这种情况下,您可以获取总和,然后将类型转换回bool以获取or操作。

import pandas as pd

df = pd.concat([left, right], 1)
df.groupby(df.columns, 1).sum().astype(bool)

Output:

        0.0   0.5    0.7
12.5   True  True   True
14.0   True  True  False
15.5  False  True  False

如果您需要以较少的特定于案例的方式查看如何执行此操作,那么再次按列分组并通过axis=1将某些内容应用于分组对象

df = pd.concat([left, right], 1)
df.groupby(df.columns, 1).apply(lambda x: x.any(1))
#        0.0   0.5    0.7
#12.5   True  True   True
#14.0   True  True  False
#15.5  False  True  False

此外,您可以定义自定义组合功能。这是一个将左帧加两倍到右帧的4倍的帧。如果只有一列,则返回左帧的2倍。

Sample Data

剩下:

      0.0  0.5
12.5    1   11
14.0    2   17
15.5    3   17

对:

      0.7  0.5
12.5    4    2
14.0    4   -1
15.5    5    5

Code

def my_func(x):
    try:
        res = x.iloc[:, 0]*2 + x.iloc[:, 1]*4
    except IndexError:
        res = x.iloc[:, 0]*2
    return res

df = pd.concat([left, right], 1)
df.groupby(df.columns, 1).apply(lambda x: my_func(x))

Output:

      0.0  0.5  0.7
12.5    2   30    8
14.0    4   30    8
15.5    6   54   10

最后,如果你想连续这样做,那么你应该使用reduce。在这里,我将5个DataFrames与上述功能结合起来。 (我只是重复正确的Frame 4x为例)

from functools import reduce

def my_comb(df_l, df_r, func):
    """ Concatenate df_l and df_r along axis=1. Apply the
    specified function.
    """
    df = pd.concat([df_l, df_r], 1)
    return df.groupby(df.columns, 1).apply(lambda x: func(x))

reduce(lambda dfl, dfr: my_comb(dfl, dfr, func=my_func), [left, right, right, right, right])
#      0.0  0.5  0.7
#12.5   16  296  176
#14.0   32  212  176
#15.5   48  572  220
© www.soinside.com 2019 - 2024. All rights reserved.