创建一个新列,该列组合了列表中其他两列的内容

时间:2016-01-05 00:28:27

标签: python pandas dataframe

说我有DataFrame如下:

enter image description here

我想创建一个新的column,其值是第二列和第三列合并为一个单元格中的列表。

即。

combined
[-8589.95, -6492.41]
[-1475.30, 249.52]

任何想法如何做到这一点?我收到这个错误:

ValueError: Length of values does not match length of index

当我尝试做这样的事情时:

DF['combined'] = [DF['chicago_bound1'], DF['chicago_bound2']]

2 个答案:

答案 0 :(得分:4)

尝试:

df['combined'] = list(zip(df.chicago_bound1, df.chicago_bound2))

df['combined'] = df.apply(lambda x: [[x.chicago_bound1, x.chicago_bound2]], axis=1)

答案 1 :(得分:2)

您可以按整数切片按位置进行选择,您可以将其放入列表中。

在这种情况下,您的选择将是df.iloc[0:2, 1:3]

foo = df.iloc[0:2, 1:3].values.tolist()
df['combined']= foo

输出:

chicago     chicago_bound1  chicago_bound2  combined
0   -7541.18    -8589.95    -6492.41    [-8589.95, -6492.41]
1   -612.89     -1475.30    249.52  [-1475.3, 249.52]