根据另一个数据框中的列名选择数据框中的行
Selecting rows in a dataframe based on the column names of another
假设我有两个 dfs
df = pd.DataFrame({'A': [1, 2, 3,4,5],
'B': [2, 4,2,4,5], 'C': [1, -1, 3,5,10],'D': [3, -4,3,7,-3]}, columns=['A', 'B', 'C', 'D'])
df = df.set_index(['A'])
df2 = pd.DataFrame({'A': [1, 2, 3,4,5],
'J': ['B', 'B','C','D','C']}, columns=['A', 'J'])
df2 = df2.set_index(['A'])
并且我想逐行使用 df2
到 select df
的列以获得以下数据帧
sel
1 2
2 4
3 3
4 7
5 10
其中前两个值来自 df
的 B 列,第三个来自 C 列,第四个来自 D 列,最后一个来自 C 列。在 pandas?
使用lookup
,indexes
在两个df
中必须相同:
print (df.lookup(df2.index, df2['J']))
[ 2 4 3 7 10]
df = pd.DataFrame({'sel':df.lookup(df2.index, df2['J'])}, index=df.index)
print (df)
sel
A
1 2
2 4
3 3
4 7
5 10
您也可以使用 np.diag
:
x, y= df2.reset_index().values.T
df= pd.DataFrame(np.diag(df.loc[x, y].values), columns=['sel'])
print(df)
sel
0 2
1 4
2 3
3 7
4 10
假设我有两个 dfs
df = pd.DataFrame({'A': [1, 2, 3,4,5],
'B': [2, 4,2,4,5], 'C': [1, -1, 3,5,10],'D': [3, -4,3,7,-3]}, columns=['A', 'B', 'C', 'D'])
df = df.set_index(['A'])
df2 = pd.DataFrame({'A': [1, 2, 3,4,5],
'J': ['B', 'B','C','D','C']}, columns=['A', 'J'])
df2 = df2.set_index(['A'])
并且我想逐行使用 df2
到 select df
的列以获得以下数据帧
sel
1 2
2 4
3 3
4 7
5 10
其中前两个值来自 df
的 B 列,第三个来自 C 列,第四个来自 D 列,最后一个来自 C 列。在 pandas?
使用lookup
,indexes
在两个df
中必须相同:
print (df.lookup(df2.index, df2['J']))
[ 2 4 3 7 10]
df = pd.DataFrame({'sel':df.lookup(df2.index, df2['J'])}, index=df.index)
print (df)
sel
A
1 2
2 4
3 3
4 7
5 10
您也可以使用 np.diag
:
x, y= df2.reset_index().values.T
df= pd.DataFrame(np.diag(df.loc[x, y].values), columns=['sel'])
print(df)
sel
0 2
1 4
2 3
3 7
4 10