我需要以某种方式对数据帧字段的字符串进行哈希处理。
我有这个 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/