在Python中使用来自其他数据帧的标题筛选数据帧

2024-05-16 21:24:51 发布

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

我正在尝试根据我之前从下面的数据帧过滤中获得的列来过滤数据帧

AA BB CC DD EE FF GG 
0  1  1  0  1  0  0

数据帧来自一个文件,其中每行中的数据为0或1,并将根据加载的文件进行更改。我使用了下面的代码来过滤这个数据帧,以便我的输出只包含值为1的列

with open('Factors.txt') as b:
    IncludedFactors = pd.read_table(b, sep=',' )
print IncludedFactors

InterestingFactors = IncludedFactors.drop(IncludedFactors.columns[~IncludedFactors.iloc[0].astype(bool)],axis=1)
print InterestingFactors

output:
BB CC EE
1  1  1

然后,我需要过滤出一个较大的数据帧,它有许多头,但是我只需要ID、Xposition、Yposition和InterestingFactors数据帧的头

下面是我尝试过的代码,但是输出仍然只包含3个标题,而不是我需要的6个标题

headers = InterestingFactors.columns.values
print headers
PivotTable = InfoTable.filter(items=['ID', 'Postion_X','Position_Y','headers'])
print PivotTable

非常感谢您对如何正确执行此操作的任何帮助


Tags: columns文件数据代码id标题eeheaders
1条回答
网友
1楼 · 发布于 2024-05-16 21:24:51

这里有一种方法可以做到这一点:

headers = InterestingFactors.columns.append(pd.Index(['ID','Postion_X','Position_Y']))
PivotTable = InfoTable.loc[:, headers]

这将从InterestingFactors中查找的列与上面提到的3列结合起来。这个Index被传递给.loc[]

这也适用于:

headers = InterestingFactors.columns
PivotTable = InfoTable.loc[:, (pd.Index(['ID','Postion_X','Position_Y']) | headers)]

用于比较的数据类型(我相信)必须相同。将3个标准列的列表转换为pd.Index将允许您在.loc[]中使用|

相关问题 更多 >