2016-07-31 8 views
-2

Ich habe folgende DatenrahmenDatenrahmen Manipulation und Aggregation

City  Status  q1 q2 Record 
0 Austin  Standard N Y Active 
1 Dallas  Standard N y Active 
2 Orlando Standard N N Active 
3 Orlando Ex   Y Y Inactive 
4 Orlando Standard N N Active 

Ich versuche, es zu manipulieren, wie folgt aussehen:

   Count % 
All Cities  5  100.0% 
Active   4  80% 
    Ex   1  20% 
    Standard  4  80% 
    Q1 = Y  1  20% 
    Q2 = Y  2  40% 
Inactive  1  20% 

ich zu einem großen Stück Code zurückgegriffen haben, die jeweils berechnet Prozent, indem jede df-Spalte in ihre Komponentenstatus zerlegt wird (zum Beispiel eine Spalte für q1yes, eine Spalte für q1no usw.) und dann einen Datenrahmen rekursiv füllt, aber ich habe das Gefühl, dass ich etwas verpassen muss.

Ich werde auch nach Stadt brauchen, um es zu brechen, aber ich möchte, dass ein Teil, um herauszufinden, bevor

Antwort

1

für mehr Hilfe bitten können Sie es auf diese Weise tun:

In [159]: df.q1 = 'Q1 = ' + df.q1.str.upper() 

In [160]: df.q2 = 'Q2 = ' + df.q2.str.upper() 

In [161]: df 
Out[161]: 
     City Status  q1  q2 Record 
0 Austin Standard Q1 = N Q2 = Y Active 
1 Dallas Standard Q1 = N Q2 = Y Active 
2 Orlando Standard Q1 = N Q2 = N Active 
3 Orlando  Ex Q1 = Y Q2 = Y Inactive 
4 Orlando Standard Q1 = N Q2 = N Active 

In [173]: r = (df.drop('City',1) 
    .....:  .apply(lambda x: x.value_counts()) 
    .....:  .apply(lambda x: x[x.first_valid_index()], axis=1) 
    .....:  .to_frame('Count') 
    .....:  .astype(np.int16) 
    .....: ) 

In [174]: r['pct'] = (r.Count/len(df) * 100).astype(str) + '%' 

In [175]: r.loc['All Cities'] = [len(df), '100.0%'] 

In [176]: r 
Out[176]: 
      Count  pct 
Active   4 80.0% 
Ex    1 20.0% 
Inactive  1 20.0% 
Q1 = N   4 80.0% 
Q1 = Y   1 20.0% 
Q2 = N   2 40.0% 
Q2 = Y   3 60.0% 
Standard  4 80.0% 
All Cities  5 100.0% 

und schließlich:

In [178]: r[~r.index.str.contains('= N')] 
Out[178]: 
      Count  pct 
Active   4 80.0% 
Ex    1 20.0% 
Inactive  1 20.0% 
Q1 = Y   1 20.0% 
Q2 = Y   3 60.0% 
Standard  4 80.0% 
All Cities  5 100.0% 
Verwandte Themen