Skip to content
Advertisement

Concat string in column values where it is missing in Python

I have a dataframe

JavaScript

I want to append string chr in column CHROM where it’s missing. I can do it in R with grepl and paste, but wanted to try in Python. I came up with these two commands, but not sure how to index the column because pd.Series is generating NaNs.

JavaScript

Advertisement

Answer

String operations in pandas are not optimized, so the best way to do what you want is via a list comprehension.

JavaScript

An equivalent pandas operation could be via mask() method.

JavaScript

A simple timeit test would show that the list comp is much faster.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement