在数据框中创建一个新列,该新列具有列表中该行其他列的值

时间:2020-07-08 07:03:31

标签: python pandas dataframe

我想改变
enter image description here

此数据到

enter image description here

我应该如何使用Apply函数来实现这一目标?

2 个答案:

答案 0 :(得分:1)

尝试一下:

df['bbox'] = df.apply(lambda x: [y for y in x], axis=1)

对于一个看起来像这样的df:

In [15]: df
Out[15]:
   a  b  c
0  1  3  1
1  2  4  1
2  3  5  1
3  4  6  1

您将获得:

In [16]: df['bbox'] = df.apply(lambda x: [y for y in x], axis=1)

In [17]: df
Out[17]:
   a  b  c       bbox
0  1  3  1  [1, 3, 1]
1  2  4  1  [2, 4, 1]
2  3  5  1  [3, 5, 1]
3  4  6  1  [4, 6, 1]

希望这会有所帮助!

答案 1 :(得分:0)

根据您的示例以获取所需的结果,您需要转换列表中的每一行。将该列表添加到新的DataFrame中。将新列表添加到DataFrame后,请应用任何计算方法(您的输出DataFrame值与输入DataFrame的值不同,因此希望您对每个单元格或行都进行了一些计算)。

import pandas as pd
data = {'x':[121,216,49],'y':[204,288,449],'w':[108,127,184]}
df = pd.DataFrame(data,columns=['x','y','w'])
new_data = [[row.to_list()] for i, row in df.iterrows()]
new_df = pd.DataFrame(new_data, columns='bbox')
print(new_df)

            bbox
0 [121, 216, 49]
1 [204, 288,449]
2 [108, 127, 184]