2016-11-14 178 views
2

創建一個頻率表,如果我有數據,如如何大熊貓蟒蛇

Col1 
A 
B 
A 
B 
A 
C 

我需要一個像

Col_value   Count 
A     3 
B     2 
C     1 

我需要col_value和計數是列名的輸出。如果需要的話

df = pd.value_counts(df.Col1).to_frame().reset_index() 
df 
A 3 
B 2 
C 1 

然後重命名列: 所以,我可以像一個[ 'col_value']

回答

3

使用value_counts訪問

df.columns = ['Col_value','Count'] 

df 
    Col_value Count 
0   A  3 
1   B  2 
2   C  1 
+0

但value_counts不提供數據幀作爲輸出 – Anup

+0

非常感謝 – Anup

0

另一種解決方案是groupby與聚集size

df = df.groupby('Col1') 
     .size() 
     .reset_index(name='Count') 
     .rename(columns={'Col1':'Col_value'}) 
print (df) 
    Col_value Count 
0   A  3 
1   B  2 
2   C  1 
0
def frequencyTable(alist): 
''' 
list -> chart 

Returns None. Side effect is printing two columns showing each number that 
is in the list, and then a column indicating how many times it was in the list. 

Example: 

>>> frequencyTable([1, 3, 3, 2]) 
ITEM FREQUENCY 
1  1 
2  1 
3  2 

''' 
    countdict = {} 

    for item in alist: 
     if item in countdict: 
      countdict[item] = countdict[item] + 1 
     else: 
      countdict[item] = 1 
    itemlist = list(countdict.keys()) 
    itemlist.sort() 

    print("ITEM", "FREQUENCY") 

    for item in itemlist: 
     print(item, " ", countdict[item]) 

    return None