Learner
Learner

Reputation: 13

"group_by" to csv format in pandas

Here is my CSV :-

csv

But when I am trying to convert this df to csv format by using g.to_csv('path_to_csv') It show's me like this :-

S_Name      Fruit

  A         Apple
  A         Apple
  A         Apple
  B         Banana
  B         Banana
  C         Chiku

I want Actual Output in csv like this:-

S_Name      Fruit

  A         Apple
            Apple
            Apple
  B         Banana
            Banana
  C         Chiku

Can anyone help me in this , where is my mistake ?

Thank You !

Upvotes: 1

Views: 62

Answers (1)

Umar.H
Umar.H

Reputation: 23099

I'm assuming your df is already with a reset index but use this if not the case

g.reset_index(inplace=True)

what we need to do is fill the whitespace of the repeated occurrences of the S_Name column

we can use a combination of shift and .ne() to get these occurance and pass the indices to a list.

idx = g[g['S_Name'].ne(g['S_Name'].shift())].index.tolist()

print(idx)
[0, 2, 4]

we then use isin to get the inverse of these and use .loc to assign whitespace values to your column spaces

g.loc[~g.index.isin(idx),'S_Name'] = ' '
print(g)
   S_Name   Fruit
0      A   Apple
1          Apple
2          Apple
3      B  Banana
4         Banana
5      C   Chiku

then you can just output to your csv

g.to_csv('filename.csv',index=False)

Upvotes: 1

Related Questions