说我有DataFrame
如下:
我想创建一个新的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']]
答案 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]