Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...