Conditionally merge columns using Pandas
1
0
Entering edit mode
8.4 years ago
frcamacho ▴ 210

I start out with this pandas dataframe:

sampleID    scaffoldID    Type   Program    Breadth  \
3   G38791    scaffold_7     4  A  73.558964  
0   G38791  scaffold_388     3      B   0.000000  
1   G38791  scaffold_777     2      B   0.000000  
2   G38791  scaffold_787     0      B   0.000000  
3   G38791    scaffold_7     4      B  73.558964

How can I conditionally merge columns? So if df['Type' ==4], I want to change Type value for that row to "Partial" then merge column value at Program and Breadth value to give a new value for the column, Type to partial_A_73.558964?

New dataframe should be:

 sampleID    scaffoldID    Type   Program    Breadth  \
3   G38791    scaffold_7     partial_A_73.558964  A  73.558964   
0   G38791  scaffold_388     3      B   0.000000   
1   G38791  scaffold_777     2      B   0.000000   
2   G38791  scaffold_787     0      B   0.000000   
3   G38791    scaffold_7     partial_B_73.558964 B  73.558964
python pandas • 24k views
ADD COMMENT
1
Entering edit mode
8.4 years ago
frcamacho ▴ 210

This code works:

df['Type'] = np.where(df['Type'] == 4, "partial"+df['Program']+"_"+df['Breadth'],df['Type'])

Other solutions are welcome!

ADD COMMENT
0
Entering edit mode

Quick question - I think mixing data types in a column is a bad idea. Is pursuing an alternative that maintains data integrity a viable option?

ADD REPLY
0
Entering edit mode

I will be dropping both Program and Breadth column which is why I needed to concat the rows. I agree with you that in general you should not mix data types but, because of the analysis I will be conducting the Type column tell us a lot about the row, especially those that are partials.

ADD REPLY
0
Entering edit mode

Hmmm. It's just a matter of personal choice, I guess. Personally, in a storage vs maintainability contest, I'd pick maintainability (especially when atomicity is at stake), but that's me being excessively obsessed with data integrity.

ADD REPLY

Login before adding your answer.

Traffic: 1534 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6