简体   繁体   English

根据另一个 dataframe 替换列中的值

[英]Replace values in a column based on another dataframe

I have a table:我有一张桌子:

Name        Profession         Character
Ben         cinematographer    Nan
Scarlett    actress            Black Widow
Robert      actor              Iron Man
Chris       actor              Thor
Kevin       producer           Nan

I created a new data frame with a column of unique values sorted in ascending order from the table above and an incremental column我创建了一个新数据框,其中包含一列从上表升序排列的唯一值和一个增量列

ID    Job
1      actor
2      actress
3      cinematographer
4      producer

Now i need to replace the values in the profession column in the original table with their corresponding ID from the new table Desired Output现在我需要用新表 Desired Output 中的相应 ID 替换原始表中的专业列中的值

Name        Profession         Character
Ben         3                  Nan
Scarlett    2                  Black Widow
Robert      1                  Iron Man
Chris       1                  Thor
Kevin       4                  Nan

code so far
df=pdf.read_csv(filename)
column = df['Profession'].unique()
new_df=pd.DataFrame(column, columns=['Job])
new_df=new_df.sort_values(['Job'])
new_df = new_df.reset_index()
new_df.columns.values[0] = 'ID'
new_df['ID'] = new_df.index + 1
df.loc[df['Profession] == new_df['Job'], 'Profession'] = new_df['ID']

The last line yeilds 'ValueError: Can only compare identically-labeled Series objects'

Try with replace then然后尝试replace

df1.Profession = df1.Profession.replace(df2.set_index('Job').ID)

暂无
暂无

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

相关问题 如何根据另一个数据框条件替换数据框列中的值 - How to replace the values in a dataframe column based on another dataframe condition 根据另一个 dataframe 中匹配的 id 替换 dataframe 列值 - Replace dataframe column values based on matching id in another dataframe 根据另一个 dataframe 更改 dataframe 列中的值 - Change values in dataframe column based on another dataframe pandas:如果该值在第二个 dataframe 中,则根据另一个 dataframe 中的条件替换列中的值 - pandas: replace values in a column based on a condition in another dataframe if that value is in the second dataframe 如何根据特定条件将数据框中的值替换为另一个数据帧中的值? - How to replace values in a dataframe with values in another dataframe based on certain condition? 根据来自另一个数据帧 python pandas 的部分字符串匹配替换列值 - Replace column values based on partial string match from another dataframe python pandas 根据另一列替换缺失值 - Replace missing values based on another column 如何基于另一个数据框设置列值 - How to set column values based on another dataframe 根据多个条件将列添加到数据框(基于另一个数据框的值) - Add column to a dataframe based on multiple conditions (values based on another dataframe) 如何根据字典键和值替换熊猫数据框列值? - How to replace pandas dataframe column values based on dictionary key and values?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM