多索引数据帧选择与rem

2024-05-28 19:05:29 发布

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

我需要一些帮助来清理有多个索引的数据帧。你知道吗

看起来像这样

                   cost
location season 
Thorp park  autumn £12
            srping £13
            summer £22
Sea life centre  summer  £34
                 spring  £43
Alton towers     and so on.............

位置和季节是索引列。我要遍历数据并删除所有没有所有三个季节的“季节”值的位置。所以“海洋生物中心”应该被拆除。你知道吗

有人能帮我吗?你知道吗

还有一个问题,我的dataframe是从groupby命令创建的,没有“cost”列的列名。这正常吗?列中有值,只是没有标题。你知道吗


Tags: 数据parklocationseasonsummerspringcostlife
2条回答

选项1
groupby+count。您可以使用结果来索引数据帧。你知道吗

df

     col
a 1    0
  2    1
b 1    3
  2    4
  3    5
c 2    7
  3    8

v = df.groupby(level=0).transform('count').values
df = df[v == 3]

df

     col
b 1    3
  2    4
  3    5

选项2
groupby+filter。这是Paul H's idea,如果他想发布,就会删除。你知道吗

df.groupby(level=0).filter(lambda g: g.count() == 3)

     col
b 1    3
  2    4
  3    5 

选项1
跳出框框思考。。。你知道吗

df.drop(df.count(level=0).col[lambda x: x < 3].index)

     col
b 1    3
  2    4
  3    5

同样的,健壮性更强一点,因为我不依赖于列中的值。你知道吗

df.drop(df.index.to_series().count(level=0).loc[lambda x: x < 3].index)

     col
b 1    3
  2    4
  3    5

选项2
季节数不确定的一般情况下的鲁棒性。
这使用Pandas版本0.21的groupby.pipe方法

df.groupby(level=0).pipe(lambda g: g.filter(lambda d: len(d) == g.size().max()))

     col
b 1    3
  2    4
  3    5

相关问题 更多 >

    热门问题