我想重新格式化一个数据帧,以便显示两列组合的计数.这是一个示例数据帧:
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作为值参数,保证使用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
标签:python,pandas,pivot,pivot-table
来源: https://codeday.me/bug/20190627/1305088.html