将Pandas DataFrame中的列合并到DataFrame中的列表列 [英] Combine columns in a Pandas DataFrame to a column of lists in a DataFrame

查看:865
本文介绍了将Pandas DataFrame中的列合并到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

对于每一行,我想将v2v3v4的值添加到列表中,并将列表中的值与v5相乘,然后将结果放入新的列v6中这样我最终得到这样的DataFrame:

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:

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

如何在Pandas中实现这一目标?

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]

这将进行列的相关乘法,将v2v3v4值放到列表列表中(逐行),并创建新的列v6.

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.

这篇关于将Pandas DataFrame中的列合并到DataFrame中的列表列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆