Reputation: 293
I have a dataframe and I need to add some columns togeather. I cant seem to get it right. This is what I have to start with:
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)
This gives me these last 2 columns of my 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]
Now I want to add the ['x_car_move_route'] and ['x_car_move_route_1'] ( later also the x_car_move_route_2 and x_car_move_route_3) togeather and I can't get it to work. I have tried.
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)
at the end I want this 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]
Any ideas?
Upvotes: 2
Views: 145
Reputation: 75080
I had this question in your prev question when you showed us a list but called it an array:
However the simplest is np.concatenate
cars[['x_car_move_route','x_car_move_route_1']].apply(np.concatenate,axis=1)
Or:
[*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())]
Upvotes: 5