在单次扫描中创建列表

问题描述 投票:0回答:1

我想根据另一列中的条件从一列创建 2 个列表。目前,我可以通过扫描数据帧两次来获取 2 个列表。

  1. 一次扫描可以得到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

请推荐。

python pandas
1个回答
0
投票

您可以通过根据

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']
© www.soinside.com 2019 - 2024. All rights reserved.