Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

python - Preparing an aggregate dataframe for publication

I have a Pandas aggregate dataframe like this:

import pandas as pd
agg_df = pd.DataFrame({'v1':['item',  'item', 'item', 'item', 'location',  'status', 'status'],
                      'v2' :['bed', 'lamp', 'candle',   'chair',  'home', 'new',   'used' ],
                    'count':['2',  '2', '2',   '1',   '7',  '4',   '3' ]})

agg_df

enter image description here

I want to prepare it for academic publication and I need a new dataframe like this:

# item     bed    2
#          lamp   2
#          candle 2
#          chair  1
# location home   7
# status   new    4
#          used   3

How can I create such a dataframe?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For display only is possible use MultiIndex:

df = agg_df.set_index(['v1','v2'])
print (df)
                count
v1       v2          
item     bed        2
         lamp       2
         candle     2
         chair      1
location home       7
status   new        4
         used       3

If need replace duplicated values use Series.duplicated with Series.mask:

agg_df['v1'] = agg_df['v1'].mask(agg_df['v1'].duplicated(),'')
print (agg_df)
         v1      v2 count
0      item     bed     2
1              lamp     2
2            candle     2
3             chair     1
4  location    home     7
5    status     new     4
6              used     3

If need remove index and columns values:

print (agg_df.to_string(index=False, header=None))
     item     bed  2
             lamp  2
           candle  2
            chair  1
 location    home  7
   status     new  4
             used  3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...