![](/img/trans.png)
[英]In python pandas, How do you eliminate rows of data that fail to meet a condition of grouped data?
[英]pandas keep both rows that meet or fail condition
對於一個看起來像這樣的 df
d = {'age' : [21, 45, 45, 5],
'salary' : [20, 40, 10, 100]}
df = pd.DataFrame(d)
df
age salary
0 21 20
1 45 40
2 45 10
3 5 100
如果滿足條件,我正在嘗試使用 boolean 添加一列
df['stat'] = df['salary'] < 40
df
age salary stat
0 21 20 True
1 45 40 False
2 45 10 True
3 5 100 False
但是,當我將相同的條件分配給變量時,我看不到 true 或 false 列
x1 = df['salary'] < 40
df[x1]
age salary
0 21 20
2 45 10
什么是保留所有行但如果滿足條件則添加列的最佳方法
如果我有多種情況,如下所示
>>> x2 = df['age'] < 25
df[x1 & x2]
age salary
0 21 20
我想返回所有行,但有一個表示 T 或 F 的 stat 列。
但是,當我將相同的條件分配給變量時,我看不到 true 或 false 列
這是因為使用df[x1]
, pandas 執行boolean 索引,您最終只會得到滿足條件的行。
保留所有行,但如果滿足條件則添加一列
使用第一種方式,您可以鏈接多個條件並將其全部分配給一個新列,而不是使用它們進行索引:
>>> df["stat"] = x1 & x2
>>> df
age salary stat
0 21 20 True
1 45 40 False
2 45 10 False
3 5 100 False
您可以在這里使用應用 function:
df['stat'] = df.apply(lambda x: (x["age"] < 25) & (x["salary"] < 40),axis = 1)
或者為了更好的性能使用 np.where 在 np.where 中你可以使用任意數量的條件。
df['stat'] = np.where(df['age'] < 25,np.where(df['salary'] < 40,True,False),False)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.