![](/img/trans.png)
[英]Pandas dataframe - How to sort (alphabetically) column values with value_counts
[英]Create column of value_counts in Pandas dataframe
我想從我的 Pandas 數據框列之一創建唯一值的計數,然后將包含這些計數的新列添加到我的原始數據框中。 我嘗試了幾種不同的方法。 我創建了一個熊貓系列,然后使用 value_counts 方法計算了計數。 我試圖將這些值合並回我的原始數據幀,但我想合並的鍵在索引(ix/loc)中。
Color Value
Red 100
Red 150
Blue 50
我想返回類似的東西:
Color Value Counts
Red 100 2
Red 150 2
Blue 50 1
df['Counts'] = df.groupby(['Color'])['Value'].transform('count')
例如,
In [102]: df = pd.DataFrame({'Color': 'Red Red Blue'.split(), 'Value': [100, 150, 50]})
In [103]: df
Out[103]:
Color Value
0 Red 100
1 Red 150
2 Blue 50
In [104]: df['Counts'] = df.groupby(['Color'])['Value'].transform('count')
In [105]: df
Out[105]:
Color Value Counts
0 Red 100 2
1 Red 150 2
2 Blue 50 1
請注意, transform('count')
忽略 NaN。 如果要計算 NaN,請使用transform(len)
。
致匿名編輯:如果您在使用transform('count')
時遇到錯誤,可能是因為您的 Pandas 版本太舊了。 以上適用於 0.15 或更高版本的熊貓。
另一種選擇:
z = df['Color'].value_counts
z1 = z.to_dict() #converts to dictionary
df['Count_Column'] = df['Color'].map(z1)
此選項將為您提供一個包含重復計數值的列,對應於“顏色”列中每個值的頻率。
這個答案使用Series.map
和Series.value_counts
。 它使用 Pandas 1.1 進行了測試。
df['counts'] = df['attribute'].map(df['attribute'].value_counts())
信用: sacuL評論
df['Counts'] = df.Color.groupby(df.Color).transform('count')
您可以對任何系列執行此操作:將其單獨分組並調用transform('count')
:
>>> series = pd.Series(['Red', 'Red', 'Blue'])
>>> series.groupby(series).transform('count')
0 2
1 2
2 1
dtype: int64
我最初的想法是使用如下所示的列表理解,但正如評論中指出的那樣,這比groupby
和transform
方法慢。 我將留下這個答案來證明什么不該做:
In [94]: df = pd.DataFrame({'Color': 'Red Red Blue'.split(), 'Value': [100, 150, 50]})
In [95]: df['Counts'] = [sum(df['Color'] == df['Color'][i]) for i in xrange(len(df))]
In [96]: df
Out[100]:
Color Value Counts
0 Red 100 2
1 Red 150 2
2 Blue 50 1
[3 rows x 3 columns]
@unutbu 的方法對於具有多列的 DataFrames 變得復雜,這使得編碼更簡單。 如果您使用的是小數據框,這會更快(見下文),否則,您應該使用NOT使用它。
In [97]: %timeit df = pd.DataFrame({'Color': 'Red Red Blue'.split(), 'Value': [100, 150, 50]}); df['Counts'] = df.groupby(['Color']).transform('count')
100 loops, best of 3: 2.87 ms per loop
In [98]: %timeit df = pd.DataFrame({'Color': 'Red Red Blue'.split(), 'Value': [100, 150, 50]}); df['Counts'] = [sum(df['Color'] == df['Color'][i]) for i in xrange(len(df))]
1000 loops, best of 3: 1.03 ms per loop
創建一個包含重復值計數的列。 這些值是從其他列計算的臨時計算。 非常快。 歸功於@ZakS。
sum_A_B = df['A']+df['B']
sum_A_B_dict = sum_A_B.value_counts().to_dict()
df['sum_A_B'] = sum_A_B.map(sum_A_B_dict)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.