gpt4 book ai didi

python - 将条件值从一列复制到另一列

转载 作者:行者123 更新时间:2023-12-03 20:06:12 25 4
gpt4 key购买 nike

给定这样的 df:

Date          Category  Debit     Credit
2020-01-05 Utility 55.32 NA
2020-01-05 Movie 20.01 NA
2020-01-05 Payment NA -255.32
2020-01-05 Grocery 97.64 NA

如何将所有负信用值移动到借方列(并删除空的贷方列)?
Date          Category  Debit     
2020-01-05 Utility 55.32
2020-01-05 Movie 20.01
2020-01-05 Payment -255.32
2020-01-05 Grocery 97.64

这将找到负值:
df.loc[df['Credit'] < 0]

但这不起作用(最小的 Pandas 技能)
def creditmover():
If df.loc[df['Credit'] < 0]:
df.loc[df['Debit']]=df.loc[df['Credit']]

谢谢!

最佳答案

根据你的逻辑,你可以这样做:

# where credit is < 0
s = df['Credit'] < 0

# copy the corresponding values
df.loc[s, 'Debit'] = df.loc[s, 'Credit']

# drop Credit
df = df.drop('Credit', axis=1)

输出:
         Date Category   Debit
0 2020-01-05 Utility 55.32
1 2020-01-05 Movie 20.01
2 2020-01-05 Payment -255.32
3 2020-01-05 Grocery 97.64

备注 : 如果 Debit总是 Na哪里 Credit<0反之亦然,那么您可以简单地执行以下操作:
df['Debit'] = df['Debit'].fillna(df['Credit'])

df = df.drop('Credit', axis=1)

关于python - 将条件值从一列复制到另一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62011588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com