首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将给定数据帧的列的选定值分配给Python中的另一个数据帧

将给定数据帧的列的选定值分配给Python中的另一个数据帧
EN

Stack Overflow用户
提问于 2019-03-17 00:48:03
回答 2查看 597关注 0票数 2

我希望将数据帧的选定列值分配给另一个数据帧。

代码语言:javascript
复制
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

我有另一个数据框架:

代码语言:javascript
复制
data2 = [['Astronomy'],['Geography'],['Geometry'],['History']]
df2 = pd.DataFrame(data2,columns=['Subjects_selected'])

df2

Subjects_selected
Astronomy
Geography
Geometry
History

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

代码语言:javascript
复制
Subjects_selected   Retrieved_Values
Astronomy                       81
Geography                       93
Geometry                        75
History                         84
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-03-17 00:50:25

使用Series.map by Series创建DataFrame.set_index并选择列Grade

代码语言:javascript
复制
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和重命名列的解决方案:

代码语言:javascript
复制
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
票数 2
EN

Stack Overflow用户

发布于 2019-03-17 01:54:04

既然您提到了select,我将使用isin,它更像选择

代码语言:javascript
复制
df.loc[df.Subjects.isin(df2.Subjects_selected)]
Out[93]: 
    Subjects  Grade
1  Geography     93
3   Geometry     75
4  Astronomy     81
6    History     84
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55202909

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档