【问题标题】:Checking for consecutive value in dataframe on python在python上检查数据框中的连续值
【发布时间】:2021-02-21 22:41:03
【问题描述】:

已编辑:我如何检查数据框中是否存在连续值并删除没有连续值的数据。

数据框如下:
动物速度年
猎鹰 380 2010
猎鹰 NaN 2011
猎鹰 380 2012
鹦鹉 26 2010
鹦鹉 90 2012
鸟 20 2010
鸟 10 2012

我想要得到的结果是丢弃在 2010 年到 2012 年之间没有连续年份的动物,例如,在上面的数据框中,结果是丢弃鹦鹉,因为它没有 2011 年的数据。

我曾尝试使用 df.groupby() 删除数据,但是,我无法在网上找到一个好的解决方案来解决这个问题。

我的数据集有 30000 多行,因此我正在考虑创建一个循环来解决这个问题。


编辑:我正在尝试使用 groupby 解决此问题并匹配不满足 3 年数据的动物

df = pd.DataFrame({'Animal': ['Falcon', 'Falcon', 'Falcon', 'Parrot', 'Parrot', 'Bird', 'Bird'],'Max Speed': [380., np.nan, 380, 26, 90, 20, 10], 'Year': [2010,2011,2012,2010,2012,2010,2012]}

grouped_test_new = df.groupby(['Animal'])

missing = grouped_test_new.filter(lambda x: len(x) < 3)

catmissing = missing['Animal'].unique().tolist()

for i in catmissing:
    index = df[df['Animal'] == i].index

df_drop = df.copy()
df_drop = df_drop.drop(index, inplace = True)

我意识到上面的方法不起作用,因为索引结果只显示了 'Bird' 的索引 5 和 6,但没有显示 'Parrot'。

【问题讨论】:

    标签: python pandas-groupby


    【解决方案1】:


    设法通过将索引转换为列表和一维列表来解决此问题

    df = pd.DataFrame({'Animal': ['Falcon', 'Falcon', 'Falcon', 'Parrot', 'Parrot', 'Bird', 'Bird'],'Max Speed': [380., np.nan, 380, 26, 90, 20, 10], 'Year': [2010,2011,2012,2010,2012,2010,2012]}
    
    grouped_test_new = df.groupby(['Animal'])
    
    missing = grouped_test_new.filter(lambda x: len(x) < 3)
    
    catmissing = missing['Animal'].unique().tolist()
    
    list = []
    for i in catmissing:
        list.append(df[df['Animal'] == i].index.tolist())
    
    one_list = sum(list,[])
    
    df_drop = df.copy()
    df_drop.drop(list, inplace = True)
    
    

    【讨论】:

      猜你喜欢
      • 2021-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-16
      • 2019-03-28
      • 1970-01-01
      相关资源
      最近更新 更多