Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

python - Combine columns in a Pandas DataFrame to a column of 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 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]

How can I achieve this in Pandas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...