在Python中,如何使用存储在另一个数据帧中的索引来提取数据帧的元素?

问题描述 投票:0回答:1

例如,我有一个10 x 2的数据框,名为The Matrix。我还有另一个3 x 1数据帧或列表Indices = [1,5,8]。索引列表或数据框中的元素1,5和8是我要从数据框Matrix中提取的元素的索引或位置。我应该如何编写代码来实现这一目标?

谢谢!

python pandas
1个回答
0
投票

一个数据框(我假设您使用的是熊猫数据框)要求每行都有一个索引。然后可以使用数据框的loc方法访问元素。

import pandas as pd
thematrix = pd.DataFrame(index=range(10),
data={'v1':[0,10,20,30,40,50,60,70,80,90],
      'v2':[1,1,1,1,1,1,1,1,1,1]})
indices = [1,5,8]
print(thematrix.loc[indices])

与列表不同,数据帧索引不必是整数,它们可以是字符串,浮点数或时间戳。另外,loc的第二个可选参数是列名。在这种情况下,您只能从第二列获取值:

thematrix = pd.DataFrame(index=['zero','one','two','three','four'],
data={'v1':[0,10,20,30,40],
      'v2':[1,1,1,1,1]})
indices = ['zero','two']
columns = ['v2']
print(thematrix.loc[indices,columns])
© www.soinside.com 2019 - 2024. All rights reserved.