pang2016 pang2016 - 23 days ago 7
Python Question

python pandas columns contain dict

I got some trouble.

import pandas
df=pandas.DataFrame([[{'a':1,'b':2},3,3],[{'a':2,'b':4},6,5]],columns=['c1','c2','c3'])
print df

c1 c2 c3
0 {u'a': 1, u'b': 2} 3 3
1 {u'a': 2, u'b': 4} 6 5


I want to get the result like this:

b c3
0 2 3
1 4 5


I try use the df.loc[:,['c1','c3']]. but I don't know next step how I should do.
thanks a lot

Answer

You can use concat with df1 created with DataFrame constructor - first convert column c1 to numpy array by values and then to list:

df=pd.DataFrame([[{'a':1,'b':2},2,3],[{'a':2,'b':4},4,5]],columns=['c1','c2','c3'])
df1 = pd.DataFrame(df.c1.values.tolist())
print (df1)
   a  b
0  1  2
1  2  4

print (pd.concat([df1[['b']], df[['c3']]], axis=1))
   b  c3
0  2   3
1  4   5