gpt4 book ai didi

python - 将给定数据框的一列的选定值分配给Python中的另一个数据框

转载 作者:太空宇宙 更新时间:2023-11-04 00:02:36 25 4
gpt4 key购买 nike

我想将数据框的选定列值分配给另一个数据框。

data = [['Math',87],['Geography',93],['Physics',72],['Geometry',75],['Astronomy',81],['English',94],['History',84]]
df = pd.DataFrame(data,columns=['Subjects','Grade'])
df

Subjects Grade
Math 87
Geography 93
Physics 72
Geometry 75
Astronomy 81
English 94
History 84

我有另一个数据框:

data2 = [['Astronomy'],['Geography'],['Geometry'],['History']]
df2 = pd.DataFrame(data2,columns=['Subjects_selected'])

df2

Subjects_selected
Astronomy
Geography
Geometry
History

如何将成绩列值作为新列元素自动分配给 df2?我希望得到:

Subjects_selected   Retrieved_Values
Astronomy 81
Geography 93
Geometry 75
History 84

最佳答案

使用Series.mapDataFrame.set_index 创建的系列并选择 Grade 列:

df2['Retrieved_Values'] = df2['Subjects_selected'].map(df.set_index('Subjects')['Grade'])
print (df2)
Subjects_selected Retrieved_Values
0 Astronomy 81
1 Geography 93
2 Geometry 75
3 History 84

另一种解决方案 DataFrame.merge并重命名列:

d = {'Subjects':'Subjects_selected','Grade':'Retrieved_Values'}
df2 = df2.merge(df.rename(columns=d), how='left')

print (df2)
Subjects_selected Retrieved_Values
0 Astronomy 81
1 Geography 93
2 Geometry 75
3 History 84

关于python - 将给定数据框的一列的选定值分配给Python中的另一个数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55202909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com