Laz*_* Xp 3 python indexing subset indices pandas
我面临的问题是,我只需要分配在不同行和列上的原始数据帧的子集.例如:
# My Original dataframe
import pandas as pd
dfTest = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]])
Run Code Online (Sandbox Code Playgroud)
输出:
0 1 2
0 1 2 3
1 4 5 6
2 7 8 9
Run Code Online (Sandbox Code Playgroud)
我可以提供一个列表,其中包含我想要的值所在的行和列索引:
array_indices = [[0,2],[1,0],[2,1]]
Run Code Online (Sandbox Code Playgroud)
我想要的输出是一系列:
3
4
8
Run Code Online (Sandbox Code Playgroud)
有人可以帮忙吗?
使用 pd.DataFrame.lookup
dfTest.lookup(*zip(*array_indices))
array([3, 4, 8])
Run Code Online (Sandbox Code Playgroud)
你可以在pd.Series构造函数中包装
pd.Series(dfTest.lookup(*zip(*array_indices)))
0 3
1 4
2 8
dtype: int64
Run Code Online (Sandbox Code Playgroud)
轻微的变种
i, j = np.array(array_indices).T
dfTest.values[i, j]
array([3, 4, 8])
Run Code Online (Sandbox Code Playgroud)
与上面类似
pd.Series(dfTest.values[i, j])
0 3
1 4
2 8
dtype: int64
Run Code Online (Sandbox Code Playgroud)