Pandas划船

2024-04-27 08:52:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用另一个数据帧的行替换数据帧中的一行,前提是它们共享一个公共列。 以下是第一个数据帧:

index    no foo
0        0   1
1        1   2
2        2   3
3        3   4
4        4   5
5        5   6

第二个数据帧:

^{pr2}$

我希望我的结果是

index    no foo
0        0   1
1        1   2
2        2   aaa
3        3   bbb
4        4   5
5        5   6

两个数据帧之间的内部合并的结果返回正确的行,但在第一个数据帧的正确索引处插入它们时遇到了问题 如有任何帮助,我们将不胜感激。
谢谢您。在


Tags: 数据noindexfoobbbaaa前提pr2
2条回答

这应该也行得通

df1['foo'] = pd.merge(df1, df2, on='no', how='left').apply(lambda r: r['foo_y'] if r['foo_y'] == r['foo_y'] else r['foo_x'], axis=1)

您可以使用apply,可能还有比这更好的方法:

In [67]:

# define a function that takes a row and tries to find a match
def func(x):
    # find if 'no' value matches, test the length of the series
    if len(df1.loc[df1.no ==x.no, 'foo']) > 0:
        return df1.loc[df1.no ==x.no, 'foo'].values[0] # return the first array value
    else:
        return x.foo # no match so return the existing value

# call apply and using a lamda apply row-wise (axis=1 means row-wise)
df.foo = df.apply(lambda row: func(row), axis=1)
df

Out[67]:

   index  no  foo
0      0   0    1
1      1   1    2
2      2   2  aaa
3      3   3  bbb
4      4   4    5
5      5   5    6

[6 rows x 3 columns]

相关问题 更多 >