迭代multiIndex数据帧

时间:2016-09-10 13:30:26

标签: python pandas dataframe multi-index

我有一个数据框,如下所示 dataframe

迭代行时遇到问题。对于每个提取的行,我想返回键值。例如,在 2016-08-31 00:00:01 条目的第二行df1& df3的罗盘值为4.0,所以我想返回具有相同罗盘值的键,即df1&在这种情况下df3 我一直在使用

迭代行
for index,row in df.iterrows():

1 个答案:

答案 0 :(得分:1)

<强>更新

好的,现在我更了解你的问题,这对你有用。 首先使用

更改数据框的形状
dfs = df.stack().swaplevel(axis=0)

这会使您的数据框看起来像:

enter image description here

然后您可以像以前一样迭代行并提取所需的信息。我只是将打印语句用于所有内容,但您可以将其放在一些更合适的数据结构中。

for index, row in dfs.iterrows():
     dup_filter = row.duplicated(keep=False)
     dfss = row_tuple[dup_filter].index.values
     print("Attribute:", index[0])
     print("Index:", index[1])
     print("Matches:", dfss, "\n")

将打印出类似

的内容
.....

Attribute: compass
Index: 5
Matches: ['df1' 'df3']

Attribute: gyro
Index: 5
Matches: ['df1' 'df3']

Attribute: accel
Index: 6
Matches: ['df1' 'df3']

....

您也可以通过

一次执行一个属性

dfs_compass = df.stack().swaplevel(axis=0).loc['compass']

并使用索引遍历行。

<强>旧

如果我正确理解你的问题,即你想要返回列的第二层上具有匹配值的行的索引,即('compass','accel','gyro')。以下将有效。

compass_match_indexes = []

for index, row in df.iterrows():
    match_filter = row[:, 'compass'].duplicated()
    if len(row[:, 'compass'][match_filter] > 0)
        compass_match_indexes.append(index)

您可以使用该列表选择您的数据框,例如df.loc[compass_match_indexes]

-

另一种方法是,您可以使用df.T获取DataFrame的转换,然后使用duplicated函数。

相关问题