gpt4 book ai didi

python - 将 Pandas 列中的列表拆分为单独的列

转载 作者:行者123 更新时间:2023-11-30 22:36:08 25 4
gpt4 key购买 nike

这是我在 pandas 数据框中的“特征”列

Feature
Cricket:82379, Kabaddi:255, Reality:4751
Cricket:15640, Wildlife:730
LiveTV:13, Football:4129
TalkShow:658, Cricket:7690
Drama:5503, Cricket:3283, Reality:1345

我想创建一个 Cricket 列并输入值 82379。

类似于下面链接中提到的情况 Splitting dictionary/list inside a Pandas Column into Separate Columns

最佳答案

假设你有:

import pandas as pd
df = pd.DataFrame.from_dict({'Freature':[{"Cricket":82379, "Kabaddi":255, "Reality":4751},{"Cricket":15640, "Wildlife":730},{"LiveTV":13, "Football":4129},{"TalkShow":658, "Cricket":7690},{"Drama":5503, "Cricket":3283, "Reality":1345}]})
df

Freature
0 {u'Cricket': 82379, u'Kabaddi': 255, u'Reality...
1 {u'Cricket': 15640, u'Wildlife': 730}
2 {u'LiveTV': 13, u'Football': 4129}
3 {u'TalkShow': 658, u'Cricket': 7690}
4 {u'Drama': 5503, u'Cricket': 3283, u'Reality':...

然后尝试:

df['Freature'].apply(pd.Series)

输出将是:

    Cricket Drama   Football    Kabaddi LiveTV  Reality TalkShow    Wildlife
0 82379.0 NaN NaN 255.0 NaN 4751.0 NaN NaN
1 15640.0 NaN NaN NaN NaN NaN NaN 730.0
2 NaN NaN 4129.0 NaN 13.0 NaN NaN NaN
3 7690.0 NaN NaN NaN NaN NaN 658.0 NaN
4 3283.0 5503.0 NaN NaN NaN 1345.0 NaN NaN

更新:

转换为字典:

new_df = df['Freature'].apply(pd.Series)
result = dict((column, list(new_df[column].dropna())) for column in new_df.columns)
result

结果的输出将是一个字典:

{'Cricket': [82379.0, 15640.0, 7690.0, 3283.0],
'Drama': [5503.0],
'Football': [4129.0],
'Kabaddi': [255.0],
'LiveTV': [13.0],
'Reality': [4751.0, 1345.0],
'TalkShow': [658.0],
'Wildlife': [730.0]}

如果Freature内容是字符串:

import pandas as pd
df = pd.DataFrame.from_dict({'Freature':["Cricket:82379, Kabaddi:255, Reality:4751","Cricket:15640, Wildlife:730","LiveTV:13, Football:4129","TalkShow:658, Cricket:7690","Drama:5503, Cricket:3283, Reality:1345"]})
df

Freature
0 Cricket:82379, Kabaddi:255, Reality:4751
1 Cricket:15640, Wildlife:730
2 LiveTV:13, Football:4129
3 TalkShow:658, Cricket:7690
4 Drama:5503, Cricket:3283, Reality:1345

然后你可以将它们转换为字典,如下所示:

for i in range(len(df)):
print(dict((e.strip().split(":")[0],int(e.strip().split(":")[1])) for e in df.iloc[i].Freature.split(",")))

它将打印所有转换后的字典:

{'Cricket': 82379, 'Kabaddi': 255, 'Reality': 4751}
{'Cricket': 15640, 'Wildlife': 730}
{'LiveTV': 13, 'Football': 4129}
{'TalkShow': 658, 'Cricket': 7690}
{'Drama': 5503, 'Cricket': 3283, 'Reality': 1345}

关于python - 将 Pandas 列中的列表拆分为单独的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44298525/

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