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

2024-06-28 11:27:51 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我有另一个数据帧:

^{pr2}$

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

Subjects_selected   Retrieved_Values
Astronomy                       81
Geography                       93
Geometry                        75
History                         84

Tags: 数据dataframedfdataenglishmathhistorypd
2条回答

既然您提到了select,我将使用isin,这是'更像select'

df.loc[df.Subjects.isin(df2.Subjects_selected)]
Out[93]: 
    Subjects  Grade
1  Geography     93
3   Geometry     75
4  Astronomy     81
6    History     84

通过^{}创建的Series使用{a1},并选择列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

另一个带有^{}和重命名列的解决方案:

^{pr2}$

相关问题 更多 >