2015-01-12 164 views
1

我有大熊貓據幀「test_df」:大熊貓數據幀:一列中創建一個從列表中的列

email      my_list 
[email protected]   [1,9,3,5] 
[email protected]   [6,3,3,15] 
[email protected]   [7,7,2,5] 
[email protected]   [5,5,5,5] 

我怎麼能有這樣的數據框如下(取第2 ELEM「my_list」的):

email      col1    col2    
[email protected]   1    9   
[email protected]   6    3 
[email protected]   7    7 
[email protected]   5    5   

我想:

test_df['col1'] = test_df['my_list'][0] 
test_df['col2'] = test_df['my_list'][1] 

但它不工作

+0

'my_list'的元素類型是什麼? IOW,'type(test_df.my_list [0])'返回的是什麼? – DSM

+0

感謝您的回答@DSM類型(test_df.my_list [0]) woshitom

回答

2

我問了一個相關的問題here,雖然我想要做的比將列表擴展到列更多,所以答案比您需要的更復雜。在你的情況下,你可以這樣做:

# Using my own example data since it's a bit tough to copy-paste 
# a printed table and have the lists show up as lists 
df = pd.DataFrame({'email': ['[email protected]', '[email protected]'], 
        'lists': [[1, 9, 3, 5], [6, 3, 3, 15]]}) 
df 
Out[14]: 
      email   lists 
0 [email protected] [1, 9, 3, 5] 
1 [email protected] [6, 3, 3, 15] 

objs = [df, pd.DataFrame(df['lists'].tolist()).iloc[:, :2]] 
pd.concat(objs, axis=1).drop('lists', axis=1) 
Out[13]: 
      email 0 1 
0 [email protected] 1 9 
1 [email protected] 6 3 
+0

(也注意:它是'列',而不是'冒號') – Marius