2016-04-14 11 views
1

Ich habe zwei Variablen,Tabellenfunktion in Python

a     b 
Less than 5  Yes 
Less than 5  No 
Less than 5  Yes 
Less than 5  No 
Less than 5  Yes 
Greater than 5  No 
Greater than 5  Yes 
Greater than 5  No 
Greater than 5  Yes 

ich einen Tisch zu bekommen, die mir zeigen würde,

    Yes  No 
Less than 5  3  2 
Greater than 5 2  2 

Ich mag im Grunde eine Tabelle Funktion von R in Python.

Kann mir jemand dabei helfen?

Dank

+2

Am besten ist es Praxis, um ein minimal reproduzierbares Beispiel zu installieren. – Dason

Antwort

0

diese Liste A und B Unter der Annahme, die gleiche Länge immer

distinct = set(a) 
for type in distinct: 
    yes = [b[i] for i in range(len(b)) if a[i] == type].count('yes') 
    no = [b[i] for i in range(len(b)) if a[i] == type].count('no') 
    print type, yes, no 

Fancy Formatierung nicht enthalten

0
import petl 

a = ['Less than 5', 'Less than 5','Less than 5','Less than 5','Less than 5', 
    'Greater than 5','Greater than 5','Greater than 5','Greater than 5',] 
b = ['Yes', 'No', 'Yes', 'No', 'Yes', 'No', 'Yes', 'No', 'Yes'] 
cols = [a, b] 
table = petl.fromcolumns(cols) 

yes_table = petl.addfield(table, 'Yes_addition', lambda rec: 1 if rec['f1'] == 'Yes' else 0) 
yes_table = petl.aggregate(yes_table, 'f0', sum, 'Yes_addition') 
yes_table = petl.rename(yes_table, 'value', 'Yes') 

no_table = petl.addfield(table, 'No_addition', lambda rec: 0 if rec['f1'] == 'Yes' else 1) 
no_table = petl.aggregate(no_table, 'f0', sum, 'No_addition') 
no_table = petl.rename(no_table, 'value', 'No') 

joined = petl.join(yes_table, no_table, key='f0') 

print petl.lookall(joined) 
as_dictionary = petl.dicts(joined) 

Die obige Ausgangs wird die folgende (wie auch die Erzeugung as_dictionary Variable wird ein Wörterbuch sein, das Sie leicht woanders in Ihrem Code verwenden können):

+------------------+-----+----+ 
| f0    | Yes | No | 
+==================+=====+====+ 
| 'Greater than 5' | 2 | 2 | 
+------------------+-----+----+ 
| 'Less than 5' | 3 | 2 | 
+------------------+-----+----+ 

Vergessen Sie nicht TLPE

pip install petl 
Verwandte Themen