如何在数据框中创建'col new'?
'col 1' 'col 2' 'col new'
0 a b [a, b]
1 c d [c, d]
2 e f [e, f]
提前感谢
答案 0 :(得分:0)
您可以使用list comprehension
将转化价值转换为list
的{{1}}:
tuple
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'>
s:
numpy array
答案 1 :(得分:0)
这是一种更简单的方法
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]