簡體   English   中英

熊貓應用多個大於和小於按特定列對行進行分組

[英]Pandas Applying multiple greater than and less than grouping rows by specific column

我正在基於一個原始熊貓數據框創建 3 個熊貓數據框。 我已經計算了與規范的標准偏差。

#Mean
stats_over_29000_mean = stats_over_29000['count'].mean().astype(int)

152542

#STDS
stats_over_29000_count_between_std = stats_over_29000_std - stats_over_29000_mean

54313

stats_over_29000_first_std = stats_over_29000_mean + stats_over_29000_count_between_std

206855

stats_over_29000_second_std = stats_over_29000_first_std + stats_over_29000_count_between_std

261168

stats_over_29000_third_std = stats_over_29000_second_std + stats_over_29000_count_between_std

315481

這適用於從 df 獲取 2 stds 下的所有行

#Select all rows where count is less than 2 standard deviations 
stats_under_2_stds = stats_over_29000[stats_over_29000['count'] < stats_over_29000_second_std]

接下來我想從 df 中選擇所有行,其中 >=2 stds 且少於 3 stds

我試過了:

stats_2_and_over_under_3_stds = stats_over_29000[stats_over_29000['count'] >= stats_over_29000_second_std < stats_over_29000_third_std]

stats_2_and_over_under_3_stds = stats_over_29000[stats_over_29000['count'] >= stats_over_29000_second_std && < stats_over_29000_third_std]

但兩者似乎都不起作用。

熊貓現在有Series.between(left, right, inclusive=True)它允許兩個兩個比較,在同一時間

在你的情況下:

stats_2_and_over_under_3_stds = \
  stats_over_29000[(stats_over_29000['count'].between(
  stats_over_29000_second_std, stats_over_29000_third_std)]

這是您在 df 上使用 2 個條件過濾的方式:

  • init df = pd.DataFrame([[1,2],[1,3],[1,5],[1,8]],columns=['A','B'])
  • 操作: res = df[(df['B']<8) & (df['B']>2)]
  • 結果 :

     AB 1 1 3 2 1 5

在你的情況下:

stats_2_and_over_under_3_stds = stats_over_29000[(stats_over_29000['count'] >= stats_over_29000_second_std) & (stats_over_29000['count'] < stats_over_29000_third_std)]

loc函數允許您應用多個條件以非常簡潔的語法過濾數據框。 我正在輸入“感興趣的列”,因為我不知道存儲值的列名。 或者,如果感興趣的列是索引,您可以在 loc 函數內直接將條件寫為(stats_over_29000 > 261168)

    stats_over_29000.loc[(stats_over_29000('column of interest') > 261168) &\
 (stats_over_29000('column of interest') < 315481)]

暫無
暫無

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

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