简体   繁体   English

如何根据公共值将数据框中列的值添加到另一个数据框中? 熊猫/蟒蛇

[英]how to add values of a column in dataframe to another dataframe based on common values? pandas/python

Two dataframes:两个数据框:

df1: df1:

Name
Sarah   
John   
J   
Fritz
Sarah
John

df2: df2:

F_Name     gender   count
Sarah      F       1000
John       M       3500
Fritz      M       12540

Aim : if df1.name is in df2.F_Name then add column gender to df1.目标:如果 df1.name 在 df2.F_Name 中,则将列性别添加到 df1。 The expected answer is:预期的答案是:

df1: df1:

Name     gender
Sarah     F
John      M
J   
Fritz     M
Sarah     F
John      M

below code gives error: "Unalignable boolean Series provided as indexer"下面的代码给出错误:“作为索引器提供的不可对齐的布尔系列”

df1['gender'] = df2[df1['Name'].isin(df2['Name'])]['gender'].values

尝试merge

df = df1.merge(df2.rename(columns = {'F_Name':'Name'}), on ='Name',how='left')

使用map

df1['gender'] = df1['Name'].map(df2.set_index('F_Name')['gender'])

暂无
暂无

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

相关问题 如何使用另一个数据框添加数据框并基于列更新公共值 - how to add a dataframe with another dataframe and updated common values based on a column 如何使用另一个数据框添加数据框并基于列添加公共列值? - how to add a dataframe with another dataframe and add common columns values based on a column? 根据python另一列中的公共值在数据框的一列中划分2个值 - Dividing 2 values in a column of dataframe based on common value in another column in python 根据另一个中的值将值添加到pandas数据帧的一列中 - Add values to one column of a pandas dataframe based on the values in another 如何根据 Pandas 中的另一个 DataFrame 更改 DataFrame 特定列中的值 - How to change values in certain column of DataFrame based on another DataFrame in Pandas 根据熊猫中数据框的另一列的值添加一列 - add a column based on the values of another column of dataframe in pandas 如何基于另一列的NaN值设置熊猫数据框中的值? - How set values in pandas dataframe based on NaN values of another column? 根据另一列中的值将列添加到Python pandas DataFrame - Add column to a Python pandas DataFrame based on values in an other column 如何根据公共列将 dataframe 的列值替换为另一个 dataframe 的值? - How do I replace column values of a dataframe with values of another dataframe based on a common column? pandas数据框根据另一数据框中的值将值追加到一列 - pandas dataframe append values to one column based on the values in another dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM