我正在尝试从具有以下结构的数组中创建数据框:
df = [[{'date_time': Timestamp('2015-05-22 05:37:59'),
'name': 'Tom',
'value': '129'},
{'date_time': Timestamp('2015-05-22 05:37:59'),
'name': 'Kate',
'value': '0'},
{'date_time': Timestamp('2015-05-22 05:37:59'),
'name': 'GroupeId',
'value': '0'}, {...}, {...}, {...}],[another list of dictionaries like the first one],[and another one]]
使用此代码:
def create_from_arr():
baby_array=pd.MultiIndex.from_tuples(df, names=['sessions', 'behaves'])
return baby_array
我有以下错误,我无法理解:
TypeError: unhashable type: 'dict'
我想要的输出是这样的:
list
date_time name value
1 0 2015-05-22 05:37:59 Tom 129
1 2015-05-22 05:37:59 Kate 0
2 2015-05-22 05:37:59 GroupeId 0
2 3 2015-05-26 05:56:59 Hence 129
4 2015-05-26 05:56:59 Kate 0
5 2015-05-26 05:56:59 Julie 0
3 ...................... ...... ......
最佳答案
我仍然不确定你到底想用 MultiIndex 做什么,但这里有一种方法可以在你的多级数组中“展平”你的字典并将你的数据正确加载到数据帧中:
将“list”和“index”更新为 MultiIndex
In [100]: data = [[{'date_time': Timestamp('2015-05-22 05:37:59'),
.....: 'name': 'Tom',
.....: 'value': '129'},
.....: {'date_time': Timestamp('2015-05-22 05:37:59'),
.....: 'name': 'Kate',
.....: 'value': '0'},
.....: {'date_time': Timestamp('2015-05-22 05:37:59'),
.....: 'name': 'GroupeId',
.....: 'value': '0'}], [{'date_time': Timestamp('2015-05-22 05:37:59'),
.....: 'name': 'Tom',
.....: 'value': '129'},
.....: {'date_time': Timestamp('2015-05-22 05:37:59'),
.....: 'name': 'Kate',
.....: 'value': '0'},
.....: {'date_time': Timestamp('2015-05-22 05:37:59'),
.....: 'name': 'GroupeId',
.....: 'value': '0'}]]
In [101]: df = pd.DataFrame(columns=['list', 'date_time', 'name', 'value'])
In [102]: for idx, each in enumerate(data, 1):
.....: temp = pd.DataFrame(each)
.....: temp['list'] = idx # manually assign "list" index
.....: df = df.append(temp, ignore_index=True)
.....:
In [103]: df = df.reset_index()
In [104]: df.set_index(['list', 'index'])
Out[104]:
date_time name value
list index
1 0 2015-05-22 05:37:59 Tom 129
1 2015-05-22 05:37:59 Kate 0
2 2015-05-22 05:37:59 GroupeId 0
2 3 2015-05-22 05:37:59 Tom 129
4 2015-05-22 05:37:59 Kate 0
5 2015-05-22 05:37:59 GroupeId 0
关于python - 来自数组的 Pandas Multiindex => TypeError : unhashable type: 'dict' ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33169701/