2017-07-05 16 views
1

データフレームに 'col new'を作成するには?データフレームにdtype配列列を作成

  'col 1' 'col 2' 'col new' 
0   a   b   [a, b] 
1   c   d   [c, d] 
2   e   f   [e, f] 

あなたはtuple sからlistに変換値とlist comprehensionを使用することができ、事前

+0

をあなたの質問は何ですか?あなたは両方のフィールドをdtypeまたはconcatしたいですか? – ammy

答えて

0

で感謝:apply

df['col new'] = [list(x) for x in zip(df['col 1'],df['col 2'])] 

print (df) 
    col 1 col 2 col new 
0  a  b [a, b] 
1  c  d [c, d] 
2  e  f [e, f] 

print (type(df.loc[0, 'col new'])) 
<class 'list'> 

別の解決策:

df['col new'] = df.apply(lambda x: [x['col 1'], x['col 2']], axis=1) 
print (df) 
    col 1 col 2 col new 
0  a  b [a, b] 
1  c  d [c, d] 
2  e  f [e, f] 

print (type(df.loc[0, 'col new'])) 
<class 'list'> 

必要numpy array sの場合:

df['col new'] = [np.array(x) for x in zip(df['col 1'],df['col 2'])] 

print (type(df.loc[0, 'col new'])) 
<class 'numpy.ndarray'> 
+0

'apply'メソッドが機能しません。 Thanks – user707711

0

ここに1つの簡単な方法だ

In [216]: df['col new'] = df[['col 1', 'col 2']].values.tolist() 

In [217]: df 
Out[217]: 
    col 1 col 2 col new 
0  a  b [a, b] 
1  c  d [c, d] 
2  e  f [e, f] 
+0

col 1とcol 2がdatetime型で、動作していない(型が変更されている)場合他のタイプでは動作するようです。 – user707711

関連する問題