![](/img/trans.png)
[英]Python - Pandas - Dataframe How to add notnull to a column when using .count
[英]Python - Pandas - Dataframe How to add variables to a column when using .count
我正在創建一個新列,該列將計算所有 ID,但排除幾行客戶 ID 具有特定前綴且沒有重復訂單的客戶
df['newcolumn'] = df[(df.notnull['Date']) & (df['ID'].str.contains('prefix')) & (df['Repeat order'] == 'No')].groupby(['ID'], as_index=False).count()
我得到以下錯誤
TypeError: 'method' object is not subscriptable
當我用 () 替換 [] 來解決上述錯誤時仍然沒有區別
我還替換了df[(df['Date'].notnull)
並得到TypeError: unsupported operand type(s) for &: 'method' and 'bool' error
這是英文class期間連貫句的編碼等價。 您試圖將這么多東西塞進一行,以至於很難說出問題出在哪里。
分解你的代碼:
cond = (
df['Date'].notnull()
& df['ID'].str.contains('prefix')
& df['Repeat order'].eq('No')
)
df['newcolumn'] = df[cond].groupby(['ID'], as_index=False).count()
注意:你原來的錯誤是因為這個:
df.notnull['Date']
df.notnull
是一種方法。 它不可下標。 您可以執行該方法並對結果下標:
df.notnull()['Date']
或者您可以從數據框中提取一列並在其上運行notnull
:
df['Date'].notnull()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.