简体   繁体   中英

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']. 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() :

#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 :

            a       b       c
time1       a1      b1      c1
time2       a2      b2      c2
time100     a100    b100    c100

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM