mobelahcen
mobelahcen

Reputation: 424

Show common values in a column once in pandas

I have a dataframe that looks like this:

df = pd.DataFrame({'key': ['K0', 'K0', 'K0', 'K1'],'cat': ['C0', 'C0', 'C1', 'C1'],'B': ['A0', 'A1', 'A2', 'A3']})
df
Out[15]: 
  key cat   B
0  K0  C0  A0
1  K0  C0  A1
2  K0  C1  A2
3  K1  C1  A3

Is it possible to convert it to:

   key cat B
0  K0  C0  A0
1          A1
2  K0  C1  A2
3  K1  C1  A3

I want to avoid showing same value of key & cat again and again and key reappears once cat changes.
It's for an excel purpose so I need it to be compatible with:

style.apply(f)
to_excel()

Upvotes: 1

Views: 458

Answers (1)

yatu
yatu

Reputation: 88236

You can use duplicated over a subset of the columns to look for duplicate values:

cols = ['key', 'cat']
df.loc[df.duplicated(subset=cols), cols] = '' 

  key cat   B
0  K0  C0  A0
1          A1
2  K0  C1  A2
3  K1  C1  A3

Upvotes: 4

Related Questions