簡體   English   中英

TypeError:無法使用 Int64Index 類型的這些索引器 [Int64Index([5], dtype='int64')] 對 Int64Index 進行位置索引

[英]TypeError: cannot do positional indexing on Int64Index with these indexers [Int64Index([5], dtype='int64')] of type Int64Index

我有一個像這樣的 dataframe(小樣本):

import pandas as pd

data = [['A', False, 2], ['A', True, 8], ['A', False, 25], ['A', False, 30], ['B', False, 4], ['B', False, 8], ['B', True, 2], ['B', False, 3]]
df = pd.DataFrame(data = data, columns = ['group', 'indicator', 'val'])

  group  indicator  val
0     A      False    2
1     A       True    8
2     A      False   25
3     A      False   30
4     B      False    4
5     B      False    8
6     B       True    2
7     B      False    3

我想 select n 行上方和下方的行,每個group都有indicator == True 例如,我想獲得 n = 1 行,這意味着對於 A 組,它將返回索引為:0、1、2 的行,對於 B 組,索引為:5、6、7 的行。我嘗試了以下代碼:

# subset each group to list
dfs = [x for _, x in df.groupby('group')] 

for i in dfs:
    # select dataframe
    df_sub = dfs[1]
    # get index of row with indicator True
    idx = df_sub.index[df_sub['indicator'] == True]
    # select n rows above and below row with True
    df_sub = df_sub.iloc[idx - 1: idx + 1]
    # combine each dataframe again
    df_merged = pd.concat(df_sub)
    
    print(df_merged)

但我收到以下錯誤:

TypeError: cannot do positional indexing on Int64Index with these indexers [Int64Index([5], dtype='int64')] of type Int64Index

這是所需的 output:

data = [['A', False, 2], ['A', True, 8], ['A', False, 25], ['B', False, 8], ['B', True, 2], ['B', False, 3]]
df_desired = pd.DataFrame(data = data, columns = ['group', 'indicator', 'val'])

  group  indicator  val
0     A      False    2
1     A       True    8
2     A      False   25
3     B      False    8
4     B       True    2
5     B      False    3

我不明白為什么會發生此錯誤以及如何解決它。 有誰知道如何解決這個問題?

您可以使用帶有 2*n+1 居中groupby.rolling的 groupby.rolling 來獲取每個 True 之前和之后的 n 行,然后執行boolean 索引

n = 1

mask = (df.groupby('group')['indicator']
          .rolling(n*2+1, center=True, min_periods=1)
          .max().droplevel(0)
          .astype(bool)
       )

out = df.loc[mask]

output:

  group  indicator  val
0     A      False    2
1     A       True    8
2     A      False   25
5     B      False    8
6     B       True    2
7     B      False    3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM