0

I have a pandas dataframe with rows representing an identifier and the columns representing a gene name. Some gene names have been duplicated, so there are multiple columns with the same name, however each row only has 1 result for 1 gene.

I want to 'merge' the columns with the same gene name, keeping any result in any of the identical columns.

I have attached an image of the .head() of the dataframe below.

enter image description here

So in the example of column name 'ACTN3 (rs1815739)' it would merge all 3 of the identical columns, and the resulting column would have all the entries in all of the rows. The entries in the rows are strings or NaNs.

I can extract all the columns for one specific gene using .loc(), and could maybe figure out a solution for that extracted data, but the dataset is very big and I am a bit over my head trying to do all the columns at once.

1 Answer 1

0

If need first not missing values per columns if exist use:

df = df.groupby(level=0, axis=1).first()
2
  • Thank you so much, that worked perfectly! I tried so many types of groupby and just couldn't get it to work. I am a bit of a python rookie, could you explain what level does in groupby? I don't quite understand it from the documentation.
    – user13593456
    Feb 15, 2021 at 12:12
  • @JamesMeroiti - I think it is necessary for general solution, level is used for MultiIndex mainly, here if no MultiIndex it is used for select columns names like first level of MultiIndex.
    – jezrael
    Feb 15, 2021 at 12:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy