gpt4 book ai didi

python - Pandas df.to_dict 在值中打印列的名称

转载 作者:行者123 更新时间:2023-12-01 00:19:42 25 4
gpt4 key购买 nike

我有以下数据框df:

                                        \def
\orth
dog one who borks
cat one who meows
...

我想把它变成以下类型的字典:

dict = {'dog': {'one', 'who', 'borks'}, 'cat': {'one', 'who', 'meows'}}

我尝试了以下代码:

df_to_dictionary = df.to_dict(orient='index')

但这会产生以下字典:

{'dog': {'\\def': 'One who borks'}, 'cat': {'\\def': 'one who meows'}}

显然上面的命令不会分割值,但我不明白为什么它在每个值中打印列名称(\def)。

最佳答案

试试这个

dct = df['\def'].str.split().agg(set).to_dict()

Out[291]: {'dog': {'borks', 'one', 'who'}, 'cat': {'meows', 'one', 'who'}}

关于python - Pandas df.to_dict 在值中打印列的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59041508/

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