我想根据另一列中的条件从一列创建 2 个列表。目前,我可以通过扫描数据帧两次来获取 2 个列表。
data = {
"co2": [95, 90, 99, 104, 105, 94, 99, 104],
"model": [
"Citigo",
"Fabia",
"Fiesta",
"Rapid",
"Focus",
"Mondeo",
"Octavia",
"B-Max",
],
"car": ["Skoda", "Skoda", "Ford", "Skoda", "Ford", "Ford", "BMW", "Ford"],
}
df = pd.DataFrame(data)
# For 2 lists
list_skoda = df.loc[df["car"] == "Skoda", "model"].tolist()
print(f"{list_skoda=}")
list_others = df.loc[df["car"] != "Skoda", "model"].tolist()
print(f"{list_others=}")
# For individual groups
df.groupby(["car"]).apply(print)
l = df.groupby(["car"])["model"].groups
print(f"{l=}") # This gives indices not names
请推荐。
您可以通过根据
car
值是否为 Skoda
进行分组来在一条语句中实现您想要的结果:
m = df["car"] == "Skoda"
list_others, list_skoda = df.groupby(m).agg(list)['model'].to_list()
print(list_skoda, list_others, sep='\n')
输出:
['Citigo', 'Fabia', 'Rapid']
['Fiesta', 'Focus', 'Mondeo', 'Octavia', 'B-Max']