1

I have a dataframe that has all unique columns, however, I have to rename the columns with their field alias after creation. Some field aliases are duplicates, in this case, those columns need to be joined together to one column. It's worth noting that in either case, the values could be strings or integers as well as contain special characters.

  Type Type Project ID
0  AS3        112    1
1  AS4        131    2
2       AS5   115    3
3  AS6        191    4
4       AS7   100    5

When I use df.groupby(df.columns, axis=1) I end up with an empty dataframe. But I'm assuming that's because groupby returns a dataframegroupby which isn't an actual dataframe? Is there an easy way to do this so my output is:

  Type Project ID
0  AS3   112    1
1  AS4   131    2
2  AS5   115    3
3  AS6   191    4
4  AS7   100    5

2 Answers 2

3

Using groupby with first ,also make sure your blank is np.nan , if not , replace it

#df=df.replace({'':'np.nan}) or df=df.mask(df=='')
df.groupby(level=0,axis=1).first()
Sign up to request clarification or add additional context in comments.

4 Comments

This doesn't appear to be working for me. I should have also noted that the dataframe is a result of a pd.concat(dfs) where dfs is a list of dataframes. Should I reassign the variable before performing this?
@AGH_TORN you should assign it back df=df.groupby(level=0,axis=1).first()
coming back to this, is there any way to maintain column order with this? Seems to be rearranging my columns at random.
@AGH_TORN (df.groupby(level=0,axis=1).first()).reindex(columns=df.columns.unique())
1

If the blank is empty string, sum will work

df.groupby(df.columns, axis = 1).sum()

    ID  Project Type
0   1   112     AS3
1   2   131     AS4
2   3   115     AS5
3   4   191     AS6
4   5   100     AS7

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.