[英]Combine columns in a Pandas DataFrame to a column of lists in a DataFrame
Consider the following DataFrame
. 请考虑以下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 of v2
, v3
, v4
to a list and multiply the values in the list with v5
and put the result into a new column v6
such that I end up with a DataFrame
like this: 对于每一行,我想将v2
, v3
, v4
的值添加到列表中,并将列表中的值与v5
相乘,并将结果放入新的列v6
,以便最终DataFrame
如下所示的DataFrame
:
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? 我怎样才能在熊猫中实现这一目标?
You can do it in one line like this: 你可以在一行中这样做:
>>> 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 does the relevant multiplication of columns, puts the v2
, v3
and v4
values out to a list of lists (row by row) and creates the new column v6
. 这会进行相关的列乘法,将v2
, v3
和v4
值放到列表列表中(逐行)并创建新列v6
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.