Reputation: 3577
Pandas 0.20.3 - Excuse the poor title. I don't know the best way to describe it.
DataFrame:
In [363]: df
Out[363]:
IP Jroid ST
0 127.0.0.3 Joid12 stq
1 127.0.0.2 Jroid2 stt
2 127.0.0.1 Jroid1 sth
3 127.0.0.1 Jroid1 stl
4 127.0.0.1 Jroid3 stj
5 127.0.0.1 Jroid2 ll
6 127.0.0.2 Jroid1 stq
7 127.0.0.1 Jroid3 stt
8 127.0.0.1 Jroid1 sth
9 127.0.0.2 Jroid1 stl
10 127.0.0.3 Jroid1 stq
11 127.0.0.3 Jroid3 stt
DataFrame grouped perfectly for my needs:
In [365]: df.groupby(['IP','Jroid','ST']).ST.agg('count')
Out[365]:
IP Jroid ST
127.0.0.1 Jroid1 sth 2
stl 1
Jroid2 ll 1
Jroid3 stj 1
stt 1
127.0.0.2 Jroid1 stl 1
stq 1
Jroid2 stt 1
127.0.0.3 Joid12 stq 1
Jroid1 stq 1
Jroid3 stt 1
Name: ST, dtype: int64
Now
df.groupby(['IP','Jroid','ST']).ST.agg('count').to_csv('/tmp/hi.csv')
renders as such:
127.0.0.1,Jroid1,sth,2
127.0.0.1,Jroid1,stl,1
127.0.0.1,Jroid2,ll,1
127.0.0.1,Jroid3,stj,1
127.0.0.1,Jroid3,stt,1
127.0.0.2,Jroid1,stl,1
127.0.0.2,Jroid1,stq,1
127.0.0.2,Jroid2,stt,1
127.0.0.3,Joid12,stq,1
127.0.0.3,Jroid1,stq,1
127.0.0.3,Jroid3,stt,1
How can I can have "to_csv" save the exact way it is represented by "df.groupby(['IP','Jroid','ST']).ST.agg('count')"? Is it possible?
Creating a new df doesn't seem to help:
print_df = df.groupby(['IP','Jroid','ST']).ST.agg('count')
print_df.to_csv('/tmp/hi.csv')
Does the same thing though.
Upvotes: 1
Views: 207
Reputation: 323316
As DeepSpace stated it won't be a valid CSV format
You can do it within .xlsx
df.to_excel('df.xlsx', engine='xlsxwriter')
Upvotes: 2