基于字段的子集数据帧

2024-10-03 21:24:43 发布

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

mukey   cokey     hzdept_r  hzdepb_r
422927  11090397    0        20
422927  11090397    20       71
422927  11090397    71       152
422927  11090398    0        18
422927  11090398    18       117
422927  11090398    117      152

我想对上面的数据帧进行子集划分,以便只选择第一组cokey(在本例中为11090397)。当然,因为这是一个示例数据集,所以解决方案需要扩展到这种数据帧的更大版本。你知道吗

在这种情况下,生成的数据集应该是:

mukey   cokey     hzdept_r  hzdepb_r
422927  11090397    0        20
422927  11090397    20       71
422927  11090397    71       152

我尝试过使用groupby,但不知道如何从中只选择第一个cokey值。你知道吗


Tags: 数据版本示例情况解决方案子集groupby本例
3条回答

如果df是示例数据帧:

cokeys = set(df.cokey) #unique keys
for k in cokeys:
    print df[df.cokey==k] #sub-dataframes

结果:

    mukey     cokey  hzdept_r  hzdepb_r
0  422927  11090397         0        20
1  422927  11090397        20        71
2  422927  11090397        71       152
    mukey     cokey  hzdept_r  hzdepb_r
3  422927  11090398         0        18
4  422927  11090398        18       117
5  422927  11090398       117       152

如果您真的只想要第一个数据帧,那么让k=df.iloc[0].cokey。你知道吗

另一种方法是只取第一个唯一值:

In [97]:

df[df['cokey'] == df['cokey'].unique()[0]]
Out[97]:
    mukey     cokey  hzdept_r  hzdepb_r
0  422927  11090397         0        20
1  422927  11090397        20        71
2  422927  11090397        71       152

您还可以使用基于整数的索引来获取第一个筛选值:

In [99]:

df[df['cokey'] == df['cokey'].iloc[0]]
Out[99]:
    mukey     cokey  hzdept_r  hzdepb_r
0  422927  11090397         0        20
1  422927  11090397        20        71
2  422927  11090397        71       152

如果要查找与df中的第一个cokey相等的df中的第一个cokey,请使用:

test[test['cokey'] == test.cokey[0]]

编辑: @dsm是对的,上面的代码会给你索引0的cokey,所以如果你的df没有一个从0开始的自动增量索引,你可能得不到真正想要的结果。而是使用:

test[test['cokey'] == test.iloc[0]['cokey']]

相关问题 更多 >