python - 一种更Pythonic的方法,将一列拆分为多列并对其中两列求和

标签 python pandas assign

示例代码:

import pandas as pd
df = pd.DataFrame({'id': [1, 2, 3], 'bbox': [[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0]]})

目标:

df = pd.DataFrame({'id': [1, 2, 3], 'bbox': [[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0]], 'x1': [1, 5, 9], 'y1': [2, 6, 10], 'x2': [4, 12, 20], 'y2': [6, 14, 22]})

换句话说,我想向数据框中添加四个整数列,其中前两列只是bbox中每个列表的前两个元素,最后一个是两个分别是每个列表的第一个和第三个元素的总和,以及第二个和第四个元素的总和。目前,我这样做:

df[['x1', 'y1', 'w', 'h']] = pd.DataFrame(df['bbox'].values.tolist(), index=df.index).astype(int)
df.assign(x2 = df['x1']+df['w'], y2 = df['y1']+df['h'])
df.drop(['w', 'h'], axis = 1) 

我觉得这有点复杂。是否有办法避免创建中间列 wh,或者会降低代码的可读性?对我来说,可读性比保存一行代码更重要,因此如果没有可读的替代方案,我会选择这个解决方案。

最佳答案

我认为你可以在第一步中创建x2y2:

df1 = pd.DataFrame(df['bbox'].values.tolist(),index=df.index).astype(int)
df[['x1', 'y1', 'x2', 'y2']] = df1
df = df.assign(x2 = df['x1']+df['x2'], y2 = df['y1']+df['y2'])

print (df)
   id                     bbox  x1  y1  x2  y2
0   1     [1.0, 2.0, 3.0, 4.0]   1   2   4   6
1   2     [5.0, 6.0, 7.0, 8.0]   5   6  12  14
2   3  [9.0, 10.0, 11.0, 12.0]   9  10  20  22

或者使用+=:

df1 = pd.DataFrame(df['bbox'].values.tolist(),index=df.index).astype(int)
df[['x1', 'y1', 'x2', 'y2']] = df1
df['x2'] += df['x1']
df['y2'] += df['y1']

关于python - 一种更Pythonic的方法,将一列拆分为多列并对其中两列求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58095086/

相关文章:

python - 是否有 Google 的 Vision API 将返回的潜在标签的完整列表?

python - 有没有更好的方法来合并具有子列表的元组的项目而不创建如下所示的新函数?

python - 替换 pandas DataFrame 中的列值

match - perl6 语法 Action : unable to make anything if not using $/

Flutter GetX RxList 分配问题

python - 在 Python 中单击按钮时隐藏标签

python - 在 Django query set order by 子句中使用绝对函数

python-3.x - Pandas:将 periodIndex 转换为多索引(年、月)

python - 获取列中唯一值的索引( Pandas )

arrays - 更新 Matlab 结构数组的每个元素中的一个字段