簡體   English   中英

如何根據 Pandas 中的條件為 dataframe 子集的列分配值?

[英]How to assign a value to a column for a subset of dataframe based on a condition in Pandas?

我有一個數據框:

df = pd.DataFrame([[0,4,0,0],
[1,5,1,0],
[2,6,0,0],
[3,7,1,0]], columns=['index', 'A', 'class', 'label'])

東風:

指數 一個 class label
0 4 0 0
1 5 1 0
2 6 0 0
3 7 1 0

如果 class 為 0 的 A 列行的平均值大於 A 列中所有數據的平均值,我想將 label 更改為 1?

如何在幾行代碼中做到這一點?

我試過這個但沒有奏效:

if df[df['class'] == 0]['A'].mean() > df['A'].mean():
   df[df['class']]['lable'] = 1

Use the following, pandas.DataFrame.groupby 'class' , get groupby.mean of each group of 'A' , check whether greater than df['A'].mean() , and pandas.Series.map that boolean series astype (int)df['class']並分配給df['label']

>>> df['label'] = df['class'].map(
        df.groupby('class')['A'].mean() > df['A'].mean()
    ).astype(int)

>>> df

   index  A  class  label
0      0  4      0      0
1      1  5      1      1
2      2  6      0      0
3      3  7      1      1

由於您只檢查class == 0,因此您需要在df['class']上添加另一個boolean mask

>>> df['label'] = (df['class'].map(
        df.groupby('class')['A'].mean() > df['A'].mean()
        ) & (~df['class'].astype(bool))
    ).astype(int)
   index  A  class  label
0      0  4      0      0
1      1  5      1      0   # because (5+7)/2 < (4+5+6+7)/4
2      2  6      0      0
3      3  7      1      0   # because (5+7)/2 < (4+5+6+7)/4

因此,即使您的代碼有效,您也不會知道它,因為條件沒有得到滿足。

如果我理解正確,如果您提到的條件已滿足,那么所有行的標簽都會更改為 1 對嗎? 在這種情況下,您所做的是正確的,但您遺漏了一些東西,代碼應如下所示:

if df[df['class'] == 0]['A'].mean() > df['A'].mean:
   df['label'] = 1

這應該有效。 您所做的不起作用,因為當您使用 df[df['class']] 時,您只是選擇了 DataFrame 的 'class' 列,因此不會調用您要修改的 'label' 列

暫無
暫無

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

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