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

indexing - Pandas merging rows with the same value and same index

I have a DataFrame with an index called SubjectID and a column Visit. Subjects have multiple Visits and either an integer value or an N/A for Value1 and Value2. I want to collapse the rows that have the same SubjectID and the same Visit number.

Here is my data frame:

SubjectID    Visit    Value1    Value2    
B1           1         1.57      N/A
B1           1         N/A       1.75
B1           2         N/A       1.56

I want to it to look like this:

Subject ID    Visit     Value1    Value2
B1            1          1.57      1.75
B1            2          N/A       1.56

I was trying to use groupby() to solve this problem but I'm not sure how to make it take into account both the index and the values in the Visit column.

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 use groupby.first or groupby.last to get the first/last non-null value for each column within the group. For the example data, the output would be the same for either method:

df = df.groupby(['SubjectID', 'Visit']).first().reset_index()

The resulting output:

  SubjectID  Visit  Value1  Value2
0        B1      1    1.57    1.75
1        B1      2     NaN    1.56

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

...