仅当满足另一列的条件时填充na

发布于 2025-01-20 12:37:12 字数 791 浏览 1 评论 0原文

我有一个看起来像这样的dataframe 测试

| sales |transactions|
|-------|------------|
|0.0    |NaN         |
|0.0    |NaN         |
|3802.29|NaN         |
|4520.35|8359        |

我正在寻找一种在“销售”列中仅具有0的行中填充NAN值的方法,而无需更改其他行。我尝试了一下:

test['transactions'] = test.apply(
        lambda row: 0 if row['sales'] == 0 else None,
        axis=1)

它适用于那些行,但问题是填充了NAN所有其他行

输出:

| sales |transactions|
|-------|------------|
|0.0    |0.0         |
|0.0    |0.0         |
|3802.29|NaN         |
|4520.35|NaN         |

预期结果:

| sales |transactions|
|-------|------------|
|0.0    |0.0         |
|0.0    |0.0         |
|3802.29|NaN         |
|4520.35|8359        |

预先感谢您。

I have a dataframe test that looks like this:

| sales |transactions|
|-------|------------|
|0.0    |NaN         |
|0.0    |NaN         |
|3802.29|NaN         |
|4520.35|8359        |

I'm looking for a way to fill the NaN values with 0 of only the rows that have 0 in the 'sales' column, without changing the other rows. I tried this:

test['transactions'] = test.apply(
        lambda row: 0 if row['sales'] == 0 else None,
        axis=1)

It works for those rows but the problem is that fills with NaN all the other rows

Output:

| sales |transactions|
|-------|------------|
|0.0    |0.0         |
|0.0    |0.0         |
|3802.29|NaN         |
|4520.35|NaN         |

Expected result:

| sales |transactions|
|-------|------------|
|0.0    |0.0         |
|0.0    |0.0         |
|3802.29|NaN         |
|4520.35|8359        |

Thank you in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

信仰 2025-01-27 12:37:12

mask

具体来说,在mask中使用其他参数,

df.assign(
    transactions=df.transactions.mask(df.sales == 0, other=0)
)

     sales  transactions
0     0.00           0.0
1     0.00           0.0
2  3802.29           NaN
3  4520.35        8359.0

如果您有一项交易,在销售额为零的情况下不是零,并且不要想要用零替换非无效事务,然后做:

mask = df.sales == 0 & df.transactions.isna()
df.assign(
    transactions=df.transactions.mask(mask, other=0)

)

mask

Specifically, use the other argument in mask

df.assign(
    transactions=df.transactions.mask(df.sales == 0, other=0)
)

     sales  transactions
0     0.00           0.0
1     0.00           0.0
2  3802.29           NaN
3  4520.35        8359.0

In the event you have a transaction that isn't null where sales are zero and don't want to replace a non-null transaction with zero then do:

mask = df.sales == 0 & df.transactions.isna()
df.assign(
    transactions=df.transactions.mask(mask, other=0)

)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文