データフレームに '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
を使用することができ、事前
データフレームに '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
を使用することができ、事前
で感謝: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'>
'apply'メソッドが機能しません。 Thanks – user707711
ここに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]
col 1とcol 2がdatetime型で、動作していない(型が変更されている)場合他のタイプでは動作するようです。 – user707711
をあなたの質問は何ですか?あなたは両方のフィールドをdtypeまたはconcatしたいですか? – ammy