Merge columns in a Pandas DataFrame with column lists in a DataFrame

Consider the following DataFrame .

 n v1 v2 v3 v4 v5 0 1 2 3 4 5 1 1 2 3 4 5 2 1 2 3 4 5 

For each row, I want to add the values v2 , v3 , v4 to the list and multiply the values ​​in the list with v5 and put the result in a new v6 column, so I end up with a DataFrame as follows:

 n v1 v6 0 1 [10, 15, 20] 1 1 [10, 15, 20] 2 1 [10, 15, 20] 

How can I achieve this in Pandas?

+6
source share
1 answer

You can do this in one line as follows:

 >>> df['v6'] = df[['v2', 'v3', 'v4']].mul(df['v5'], axis=0).values.tolist() >>> df v1 v2 v3 v4 v5 v6 0 1 2 3 4 5 [10, 15, 20] 1 1 2 3 4 5 [10, 15, 20] 2 1 2 3 4 5 [10, 15, 20] 

This leads to the corresponding multiplication of the columns, displays the values v2 , v3 and v4 in the list of lists (row by row) and creates a new column v6 .

+14
source

Source: https://habr.com/ru/post/978716/


All Articles