熊猫行操纵

时间:2014-03-20 21:11:55

标签: python pandas

我正在尝试将数据框中的行替换为另一个数据框的行,只有它们共享一个公共列。 这是第一个数据帧:

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

和第二个数据帧:

index    no foo
0        2  aaa
1        3  bbb
2       22    3
3       33    4
4       44    5
5       55    6

我希望我的结果是

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

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

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

您可以使用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]