我是一个动态填充的数据结构,因此密钥和子密钥的数量是未知的。我想把它转换成Pandas df。结构看起来像这样
datastore = {
"user1":{
"time1":[1,2,3,4],
"time2":[5,6,7,8],
"time3":[1,2,3,4] },
"user2":{
"time1":[1,2,3,4],
"time2":[5,6,7,8] }
}
带有值列表的dicts的词典
我想把它转换成像这样的pandas
index users times x y z k
0 user1 time1 1 2 3 4
1 user1 time2 5 6 7 8
2 user1 time3 1 2 3 4
3 user2 time1 1 2 3 4
4 user2 time2 5 6 7 8
....
我已尝试过pd.DataFrame(dict),from_dict方法,但无法使其正常工作。任何帮助将不胜感激。
编辑:抱歉语法错误,已修复
答案 0 :(得分:2)
这是一种方法
datastore = {
"user1":{
"time1":[1,2,3,4],
"time2":[5,6,7,8],
"time3":[1,2,3,4] },
"user2":{
"time1":[1,2,3,4],
"time2":[5,6,7,8]}
}
我们可以使用pd.DataFrame()和dict然后stack()然后reset_index()它
df = pd.DataFrame(datastore).stack().reset_index()
print(df)
level_0 level_1 0
0 time1 user1 [1, 2, 3, 4]
1 time1 user2 [1, 2, 3, 4]
2 time2 user1 [5, 6, 7, 8]
3 time2 user2 [5, 6, 7, 8]
4 time3 user1 [1, 2, 3, 4]
现在我们分开'在0中的列表,应用pd.Series,然后将其加入到level_1和level_2。一些列重命名,我们已完成
df = df[['level_1', 'level_0']].join(df[0].apply(pd.Series))
df.columns = ['users', 'times', 'x', 'y', 'z', 'k']
print(df)
users times x y z k
0 user1 time1 1 2 3 4
1 user2 time1 1 2 3 4
2 user1 time2 5 6 7 8
3 user2 time2 5 6 7 8
4 user1 time3 1 2 3 4
答案 1 :(得分:2)
选项1
pd.DataFrame.from_dict(datastore, 'index').stack() \
.rename_axis(['users', 'times']) \
.apply(pd.Series, index=list('xyzk')).reset_index()
users times x y z k
0 user1 time1 1 2 3 4
1 user1 time2 5 6 7 8
2 user1 time3 1 2 3 4
3 user2 time1 1 2 3 4
4 user2 time2 5 6 7 8
选项2
pd.DataFrame(
[[u, t] + l for u, td in datastore.items() for t, l in td.items()],
columns='users times x y z k'.split()
)
users times x y z k
0 user1 time1 1 2 3 4
1 user1 time2 5 6 7 8
2 user1 time3 1 2 3 4
3 user2 time1 1 2 3 4
4 user2 time2 5 6 7 8
计时
%timeit pd.DataFrame.from_dict(datastore, 'index').stack().rename_axis(['users', 'times']).apply(pd.Series, index=list('xyzk')).reset_index()
%timeit pd.DataFrame([[u, t] + l for u, td in datastore.items() for t, l in td.items()], columns='users timets x y z k'.split())
100 loops, best of 3: 2.72 ms per loop
1000 loops, best of 3: 556 µs per loop
<强> DEBUG 强>
如果您复制并粘贴此代码......它应该运行。请尝试并报告它确实已经运行。
import pandas as pd
datastore = {
"user1":{
"time1":[1,2,3,4],
"time2":[5,6,7,8],
"time3":[1,2,3,4] },
"user2":{
"time1":[1,2,3,4],
"time2":[5,6,7,8]}
}
pd.DataFrame.from_dict(datastore, 'index').stack() \
.rename_axis(['users', 'times']) \
.apply(pd.Series, index=list('xyzk')).reset_index()