【发布时间】:2020-12-14 12:41:58
【问题描述】:
我有一个如下的数据框:
tags categories classification
0 label ['legislative',
'law, govt and
politics', 'exe... None
0 document ['legislative',
'law, govt and politics',
'exe... NaN
0 text ['legislative', 'law,
govt and politics',
'exe... NaN
0 paper ['legislative', 'law,
govt and
politics', 'exe... NaN
0 poster ['legislative', 'law,
govt and politics', 'exe... NaN
我想创建一个新的数据框,我可以将上面的数据框折叠成下面的数据框,以便将“标签”和“分类”列的列元素转换为具有列表格式的单个项目的单行,例如
tags categories classification
0 ['label', ['legislative', ['None','NaN',
'document', 'law, govt and 'NaN','NaN',
'text', politics', 'exe... 'NaN']
'paper',poster']
我该怎么做呢?我如何使用堆栈或分组函数来获得结果?提前致谢。
*这是 df.to_dict() 的结果
{'tags': {0: ' letter',
1: ' head',
2: ' water',
3: ' art',
4: ' indoors',
5: ' flyer',
6: ' poster',
...},
'categories': {0: "['legislative', 'law, govt and politics',
'executive branch', 'work', 'society', 'government']",
1: "['unrest and war', 'society', 'religion and spirituality',
'buddhism']",
2: '[]',
3: '[]',
4: "['unemployment', 'society', 'law, govt and politics',
'foreign policy', 'work', 'politics', 'armed forces']",
5: '[]',
6: "['sports', 'law, govt and politics', 'wrestling']",
...},
'classfication': {0: nan,
1: nan,
2: nan,
3: nan,
4: nan,
5: nan,
6: nan,
...}}
【问题讨论】:
-
你能粘贴
df.to_dict()的结果吗,df是你的数据框吗? -
你能说得更清楚点吗?我无法彻底理解你的任务。我想你也想折叠
classification专栏吧? -
@ipj 我已经粘贴了结果
标签: python pandas group-by jupyter-notebook series