python-3.x 如何通过查看另一列的值来查找列的索引

t98cgbkg  于 2023-02-26  发布在  Python
关注(0)|答案(1)|浏览(110)

我有两个 Dataframe ,df1和df2。

df1 =  "R" : ["0.2","0.4","0.55"]
         "Aa" : ["1","2","3']
         "Ba" : ["5","6","6"]
 
df2 = "Rate" : ["0.2","0.55","0.2"]
       "C"   :["Aa","Aa","Ba"]

我希望代码查看C中的值,并返回与C列值完全匹配的df1列索引
预期产出:

C

Aa 1
Aa 1
Ba 2
dfty9e19

dfty9e191#

在列名及其位置之间应用Map:

col_map = dict(zip(df1.columns, range(df1.columns.size)))
c_idx = pd.Series(df2['C'].map(col_map).values, index=df2['C'].values)
print(c_idx)
Aa    1
Aa    1
Ba    2

相关问题