選項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()
你的「口授詞典」在語法上是不正確的。我們會浪費我們的時間在周圍放置引號,逗號和冒號。請清理它。 – DyZ
編輯語法正確,感謝您的輸入 – someRandomGuy
這個問題似乎相似,可能會有所幫助https://stackoverflow.com/questions/13575090/construct-pandas-dataframe-from-items-in-nested-dictionary – Hatshepsut