這是我的代碼,該工程直到df=pd.df,如果我嘗試print((df.loc[("invoice type")])了,如果,代碼作業前,但是當我使用的,如果給我的錯誤"Key Error: ′type′"
,當我groupby列名型別出現在其他列的下方。
我需要的是查找包含單詞和數字的名稱型別,并invoice type-5僅通過使用 if 進行搜索來列印第 2 列的值。
df = pd.read_excel("example.xlsx", header=0)
df = df.gropuby("type")[["column 2","column 3", "column 4"]].sum()
df = pd.DataFrame(df)
if "invoice type - 5" in df["type"]:
print((df.loc[("invoice type")])
uj5u.com熱心網友回復:
首先,您不想使用df[type]- 您想使用df['type'](注意引號)或df.type.
其次,您可以檢查if "your string" in df.your_column. 您需要df.your_column.str.contains("your string")改用:
if df['type'].str.contains("invoice type - 5").any():
print((df.loc[("invoice type")])
uj5u.com熱心網友回復:
讓我們as_type=False在 groupby 中使用然后query過濾資料框 groupby 結果:
df.groupby('type', as_index=False)[["column 2","column 3", "column 4"]]\
.sum().query('type == "invoice type - 5"')
MVCE:
df = pd.DataFrame({'type':np.random.choice([*'abcde'], 100),
'col1':np.random.random(100),
'col2':np.random.random(100)})
df.groupby('type', as_index=False)[['col1', 'col2']]\
.sum().query('type == "a"')
輸出:
type col1 col2
0 a 9.226583 8.052578
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/399351.html
