python dataframe两列相乘_python – 计算两个Dataframe列之间的组合

本文介绍如何使用Pandas的crosstab函数计算DataFrame中列'a'和'c'的组合计数,同时处理缺失值(NaN)。通过设置dropna参数为False,可以保留包含NaN值的组合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我想重新格式化一个数据帧,以便显示两列组合的计数.这是一个示例数据帧:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值