这是我的代码,直到df=pd.df为止,如果我在if之前尝试使用print((df.loc[("invoice type")]),那么代码就能工作,但是当我使用if给出错误"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")])发布于 2021-12-31 15:56:08
首先,您不想使用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")])发布于 2021-12-31 16:40:04
让我们在groupby中使用as_type=False,然后使用query过滤数据组的结果:
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.052578https://stackoverflow.com/questions/70543793
复制相似问题