gpt4 book ai didi

python - 组合 Pandas 中由 numpy 数组组成的列

转载 作者:行者123 更新时间:2023-12-02 02:18:18 25 4
gpt4 key购买 nike

我有一个数据框,我需要添加一些列。我似乎无法正确理解。这就是我必须开始的:

cars = pd.DataFrame({'x_now':    np.repeat(1,10),
'y_now': np.arange(1,11),

'x_1_goal': np.repeat(1,10),
'y_1_goal': np.repeat(10,10),

'x_2_goal': np.repeat(4, 10),
'y_2_goal': np.repeat(10, 10),

'x_3_goal': np.repeat(4, 10),
'y_3_goal': np.arange(22,12,-1)})

def route(row, var,variabel_text_1, variabel_text_2):
var2 = 'y' if var == 'x' else 'x'

now, now2 = row[f'{var}{variabel_text_1}'], row[f'{var2}{variabel_text_1}']
goal, goal2 = row[f'{var}{variabel_text_2}'], row[f'{var2}{variabel_text_2}']
diff, diff2 = goal - now, goal2 - now2

if diff == 0:
result = np.array([now] * abs(diff2)).astype(int)
else:
result = 1 + np.arange(now, goal, diff / abs(diff)).astype(int)
return result

cars['x_car_move_route'] = cars.apply(route, args=('x','_now' , '_1_goal'), axis=1)
cars['x_car_move_route_1'] = cars.apply(route, args=('x','_1_goal', '_2_goal'), axis=1)

这给了我 DataFrame 的最后两列:

         x_car_move_route          x_car_move_route_1
0 [1, 1, 1, 1, 1, 1, 1, 1, 1] [2, 3, 4]
1 [1, 1, 1, 1, 1, 1, 1, 1] [2, 3, 4]
2 [1, 1, 1, 1, 1, 1, 1] [2, 3, 4]
3 [1, 1, 1, 1, 1, 1] [2, 3, 4]
4 [1, 1, 1, 1, 1] [2, 3, 4]
5 [1, 1, 1, 1] [2, 3, 4]
6 [1, 1, 1] [2, 3, 4]
7 [1, 1] [2, 3, 4]
8 [1] [2, 3, 4]
9 [] [2, 3, 4]

现在我想添加 ['x_car_move_route'] 和 ['x_car_move_route_1'] (后来还有 x_car_move_route_2 和 x_car_move_route_3)在一起,但我无法让它工作。我已经尝试过。

cars['x_car_route_total'] = cars['x_car_move_route'] + cars['x_car_move_route_1']
cars['x_car_route_total'] = cars['x_car_move_route','x_car_move_route_1','x_car_move_route_2'].sum(1)

最后我想要这个DataFrame

                  x_car_route_total          
0 [1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4]
1 [1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4]
2 [1, 1, 1, 1, 1, 1, 1, 2, 3, 4]
3 [1, 1, 1, 1, 1, 1, 2, 3, 4]
4 [1, 1, 1, 1, 1, 2, 3, 4]
5 [1, 1, 1, 1, 2, 3, 4]
6 [1, 1, 1, 2, 3, 4]
7 [1, 1, 2, 3, 4]
8 [1, 2, 3, 4]
9 [2, 3, 4]

有什么想法吗?

最佳答案

当您向我们展示一个列表但将其称为数组时,我在上一个问题中遇到了这个问题:

但是最简单的是np.concatenate

cars[['x_car_move_route','x_car_move_route_1']].apply(np.concatenate,axis=1)

或者:

[*map(np.concatenate,cars[['x_car_move_route','x_car_move_route_1']].to_numpy())]

0    [1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4]
1 [1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4]
2 [1, 1, 1, 1, 1, 1, 1, 2, 3, 4]
3 [1, 1, 1, 1, 1, 1, 2, 3, 4]
4 [1, 1, 1, 1, 1, 2, 3, 4]
5 [1, 1, 1, 1, 2, 3, 4]
6 [1, 1, 1, 2, 3, 4]
7 [1, 1, 2, 3, 4]
8 [1, 2, 3, 4]
9 [2, 3, 4]
dtype: object

#cars['x_car_route_total'] = (cars[['x_car_move_route','x_car_move_route_1']]
# .apply(np.concatenate,axis=1))

#cars['x_car_route_total'] = [*map(np.concatenate,
#cars[['x_car_move_route','x_car_move_route_1']].to_numpy())]

关于python - 组合 Pandas 中由 numpy 数组组成的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66833953/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com