繁体   English   中英

append 如果 pandas 中没有重复,则从一个 df 到另一个的行值

[英]append row values from one df to another if no duplicates in pandas

我有这两个 df


df1 = pd.DataFrame({'pupil': ["sarah", "john", "fred"],
                  'class': ["1a", "1a", "1a"]})


df2 = pd.DataFrame({'pupil_mixed': ["sarah", "john", "lex"],
                  'class': ["1a", "1c", "1a"]})


如果值不重复,我想将 append 从 df2 的“pupil_mixed”列到 df1 中的“pupil”列的行值

期望的结果:

df1 = pd.DataFrame({'pupil': ["sarah", "john", "fred", 'lex'],
                  'class': ["1a", "1a", "1a", NaN]})


我用appendloc

df1 = df1.append(df2.loc[df2['pupil_mixed'] != df1['pupil'] ])

它只是将另一列附加到具有匹配行值的 df,并将不匹配的行值更改为 NaN

    pupil   class   pupil_mixed
0   sarah   1a      NaN
1   john    1a      NaN
2   fred    1a      NaN
2   NaN     1a      lex




您可以使用concat + drop_duplicates

res = pd.concat((df1, df2['pupil_mixed'].to_frame('pupil'))).drop_duplicates('pupil')

print(res)

Output

   pupil class
0  sarah    1a
1   john    1a
2   fred    1a
2    lex   NaN

作为替代方案,您可以先过滤(使用isin )然后连接:

# filter the rows in df2, rename the column pupil_mixed
filtered = df2.loc[~df2['pupil_mixed'].isin(df1['pupil'])]

# create a new single column DataFrame with the pupil column
res = pd.concat((df1, filtered['pupil_mixed'].to_frame('pupil')))

print(res)

两种解决方案都使用to_frame和 name 参数,有效地更改名。

# distinct df1 & df2
df1['tag'] = 1
df2['tag'] = 2

# change the column name the same
df2.columns = df1.columns
df1 = df1.append(df2)
# drop_duplicates by keep df1
df1 = df1.drop_duplicates('pupil', keep='first')

# set tag == 2, class is null
cond = df1['tag'] == 2
df1.loc[cond, 'class'] = np.nan
del df1['tag']

print(df1)

output:

print(df1)

   pupil class
0  sarah    1a
1   john    1a
2   fred    1a
3    lex   NaN

在 df2 中重命名pupil_mixed后,您可以使用合并:

df1.merge(df2["pupil_mixed"].rename("pupil"), how="outer")

   pupil    class
0   sarah   1a
1   john    1a
2   fred    1a
3   lex    NaN

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM