在数据帧中创建 dtype 数组列



如何在数据帧中创建"col new"?

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

提前致谢

这是一个更简单的方法

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]

您可以将list comprehensiontuples 的转换值一起使用list

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'>

apply的另一个解决方案:

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

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'>

最新更新