[英]Counting combinations between two Dataframe columns
我想重新格式化一個數據幀,以便顯示兩列組合的計數。 這是一個示例數據幀:
my_df = pd.DataFrame({'a': ['first', 'second', 'first', 'first', 'third', 'first'],
'b': ['foo', 'foo', 'bar', 'bar', 'baz', 'baz'],
'c': ['do', 're', 'mi', 'do', 're', 'mi'],
'e': ['this', 'this', 'that', 'this', 'those', 'this']})
看起來像這樣:
a b c e
0 first foo do this
1 second foo re this
2 first bar mi that
3 first bar do this
4 third baz re those
5 first baz mi this
我希望它創建一個新的數據框,計算列a
和c
之間的組合,如下所示:
c do mi re
a
first 2.0 2.0 NaN
second NaN NaN 1.0
third NaN NaN 1.0
如果我將values
參數設置為等於其他列,我可以使用pivot_table
執行此操作:
my_pivot_count1 = my_df.pivot_table(values='b', index='a', columns='c', aggfunc='count')
這樣的問題是列'b'可能在其中具有nan
值,在這種情況下,該組合將不被計算。 例如,如果my_df
看起來像這樣:
a b c e
0 first foo do this
1 second foo re this
2 first bar mi that
3 first bar do this
4 third baz re those
5 first NaN mi this
我對my_df.pivot_table
調用給出了:
first 2.0 1.0 NaN
second NaN NaN 1.0
third NaN NaN 1.0
我現在通過將values
參數設置為我引入my_df
的新列來使用b
作為values
參數,保證使用my_df['count'] = 1
或my_df.reset_index()
,但有沒有辦法得到我想要的東西,而不必添加一列,只使用列a
和c
?
pandas.crosstab
有一個dropna
參數,默認設置為True
,但在你的情況下你可以傳遞False
:
pd.crosstab(df['a'], df['c'], dropna=False)
# c do mi re
# a
# first 2 2 0
# second 0 0 1
# third 0 0 1
我只是使用groupby
/ unstack
:
df.groupby(by=['a', 'c']).size().unstack(level='c')
c do mi re
a
first 2.0 2.0 NaN
second NaN NaN 1.0
third NaN NaN 1.0
你可以使用fillna
和astype
N = (
df.groupby(by=['a', 'c'])
.size()
.unstack(level='c')
.fillna(0)
.astype(int)
)
c do mi re
a
first 2 2 0
second 0 0 1
third 0 0 1
您可以添加.fillna('x')
后my_df
不改變基礎數據框本身。
my_pivot_count1 = my_df.fillna('x').pivot_table(values='b', index='a', columns='c',aggfunc='count')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.