将 Pandas DataFrame 中的列组合到 DataFrame 中的一列列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27145148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 22:42:42  来源:igfitidea点击:

Combine columns in a Pandas DataFrame to a column of lists in a DataFrame

pythonlistpandasdataframe

提问by kasperhj

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, v4to a list and multiply the values in the list with v5and put the result into a new column v6such that I end up with a DataFramelike this:

对于每一行,我想补充的价值v2v3v4以在列表中的列表,并乘值v5,并把结果放入一个新列v6,这样我最终有一个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?

我怎样才能在 Pandas 中实现这一点?

回答by Alex Riley

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, v3and v4values out to a list of lists (row by row) and creates the new column v6.

这确实列,会将相关乘法v2v3v4值出列表(逐行)的列表,并创建新列v6