[英]Need to convert a dictionary which contains two lists into Pandas DataFrame
So the dictionary I got is as below:所以我得到的字典如下:
{'a': [[time1, a1], [time2, a2],[time100,a100]], 'b': [[time1, b1], [time2, b2],[time100,b100]], 'c': [[time1, c1], [time2, c2],[time100,c100]]}
The first item of every list is time in Unix timestamps and I'd like the time to be every row and columns = ['a','b','c'].每个列表的第一项是 Unix 时间戳中的时间,我希望时间是每一行和每列 = ['a','b','c']。 Also the second item in every list to be in each of their respected cell.
每个列表中的第二个项目也将在每个受尊重的单元格中。 Expected Results:
预期成绩:
a b c
time1. a1. b1. c1
time2. a2. b2 c2
time100
Essentially the time in every list is the same regardless of the key.I want to pick the time out and put the second item in each list to their each respected column.基本上每个列表中的时间都是相同的,无论键是什么。我想选择超时并将每个列表中的第二个项目放到他们每个尊重的列中。 How does the code look like?
代码看起来如何?
d={'a': [['time1', 'a1'], ['time2', 'a2'],['time100','a100']], 'b': [['time1', 'b1'], ['time2', 'b2'],['time100','b100']], 'c': [['time1', 'c1'], ['time2', 'c2'],['time100','c100']]}
try via DataFrame()
and apply()
and reset_index()
:通过
DataFrame()
和apply()
和reset_index()
尝试:
#import pandas as pd
df=pd.DataFrame(d).apply(pd.Series.explode).reset_index(drop=True)
#you can also use agg() in place of apply()
Now we will filter out result:现在我们将过滤掉结果:
c=df.index%2==0
df=df[~c].set_index(df.loc[c,'a'].values)
#OR
df=df[~c].set_index(df[c]['a'].values)
output of df
: output 的
df
:
a b c
time1 a1 b1 c1
time2 a2 b2 c2
time100 a100 b100 c100
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.