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
132 views
in Technique[技术] by (71.8m points)

python - mix the information of all columns in a single column

I have a dataset like this:

df = pd.DataFrame({'ID':["a"," b", "c","d", "e"],
               'P1': [10, 28, 34, 56, 78],
              'P2':[ 90, 54, 54, 32, 16],
              'P3':[14, 15, 24, 90,34]})

which contains the grades of students for each problem. I need to creat a new column named "Notes" which contains the grades of all problems in one column. the output must look like this: enter image description here

question from:https://stackoverflow.com/questions/65869962/mix-the-information-of-all-columns-in-a-single-column

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

1 Reply

0 votes
by (71.8m points)

Use:

#Calculate Total
df['Total'] = df.filter(regex='P').sum(axis=1)
#Create Notes
df['Notes'] = df.filter(regex='P').astype(str)
    .apply(lambda row: ','.join(row.index + ';' + row), axis=1)
print(df)


   ID  P1  P2  P3  Total              Notes
0   a  10  90  14    114  P1;10,P2;90,P3;14
1   b  28  54  15     97  P1;28,P2;54,P3;15
2   c  34  54  24    112  P1;34,P2;54,P3;24
3   d  56  32  90    178  P1;56,P2;32,P3;90
4   e  78  16  34    128  P1;78,P2;16,P3;34

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

...