gpt4 book ai didi

python - 如何在 Python 中散列数据帧的字符串?

转载 作者:行者123 更新时间:2023-12-04 07:47:59 25 4
gpt4 key购买 nike

我需要以某种方式散列数据框字段的字符串。
我有这个 df:

cars =            ['Tesla', 'Renault', 'Tesla', 'Fiat', 'Audi', 'Tesla', 'Mercedes', 'Mercedes']
included_colors = ['red', 'green', np.nan, np.nan, 'yellow', 'black', np.nan, 'orange']
data = {'Cars': cars, 'Included Colors': included_colors}
df = pd.DataFrame (data, columns = ['Cars', 'Included Colors'])
它看起来像这样:
       Cars Included Colors
0 Tesla red
1 Renault green
2 Tesla NaN
3 Fiat NaN
4 Audi yellow
5 Tesla black
6 Mercedes NaN
7 Mercedes orange
我正在尝试以这种方式创建在这种情况下有用的字典或其他形式的数据结构:
这样我终于可以让汽车和所有相关的颜色匹配,就像在这个例子中一样:
Tesla - red, black
Renault - green
Fiat - np.nan
Audi - yellow
Mercedes - orange
我试过这段代码,但我不知道如何继续......:
all_cars = df['Cars'].tolist() # extract all the cars from the df in a list
all_cars = list(dict.fromkeys(all_cars)) # make them unique

dis = {}
for car in all_cars:
mask = (df['Cars'] == car)
dis[df.loc[mask, 'Cars']] = df.loc[mask, 'Included Colors']

它不必是字典,它可以是任何东西,只要匹配所有这些键值即可。我只是认为这种数据结构适合。
如何使这项工作?非常感谢!!!!

最佳答案

您可以使用 groupby()并聚合到 list .然后创建输出字典:

x = df.groupby("Cars", as_index=False).agg(list)
out = dict(zip(x.Cars, x["Included Colors"]))
print(out)
打印:
{'Audi': ['yellow'], 'Fiat': [nan], 'Mercedes': [nan, 'orange'], 'Renault': ['green'], 'Tesla': ['red', nan, 'black']}

感谢@QuangHoang 一个简短的回答:
print(df.groupby("Cars")['Included Colors'].agg(list).to_dict())

关于python - 如何在 Python 中散列数据帧的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67115484/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com