简体   繁体   English

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

[英]Copy conditional values from one column to another

Given a df like this:给定这样的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

How do I move all negative Credit values to the Debit column (and delete the empty Credit column)?如何将所有负信用值移动到借方列(并删除空的信用列)?

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    

This will find the negative values:这将找到负值:

df.loc[df['Credit'] < 0]

But this doesn't work (minimal pandas skills)但这不起作用(最小的 pandas 技能)

def creditmover():
    If df.loc[df['Credit'] < 0]:
        df.loc[df['Debit']]=df.loc[df['Credit']]

Thanks!谢谢!

According to your logic, you could do:根据你的逻辑,你可以这样做:

# 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)

Output: Output:

         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

Note : If Debit is always Na wherever Credit is <0 and vise versa, then you can simply do:注意:如果在Credit <0的情况下, Debit始终为Na ,反之亦然,那么您可以简单地执行以下操作:

df['Debit'] = df['Debit'].fillna(df['Credit'])

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

We can do pop我们可以做pop

df.loc[df.pop('Credit')<=0,'Debit']=df.Credit
df
         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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将值从一个 dataframe 列复制到另一列 - Copy values from one dataframe column to another 如何根据列从另一个数据集中复制粘贴值 - How to copy paste values from another dataset conditional on a column 如何在另一列的条件下从一列中获取值的总和 - How to get the sum of values from one column with the conditional of another column 如果值等于某个数字,则将值从一列复制到另一列 - Copy values from one column to another if values equal to a certain number 使用openpyxl将单元格值列从一个工作簿复制到另一个工作簿 - Copy column of cell values from one workbook to another with openpyxl Pandas 有条件地将值从一列复制到另一行 - Pandas conditionally copy values from one column to another row 根据 Pandas 中的列值将内容从一个 Dataframe 复制到另一个 Dataframe - Copy contents from one Dataframe to another based on column values in Pandas 如何根据 pandas 中两个不同列的条件将值从一列复制到另一列? - how to copy values from one column into another column based on conditions of two different columns in pandas? 创建一个新的 pandas dataframe 列,其中包含一个附加值,然后是其下方另一列的值的副本 - Creating a new pandas dataframe column with one added value, then a copy of values from another column underneath it 如何根据值之间的差异将值从一个 dataframe 列复制到另一列 - How can I copy values from one dataframe column to another based on the difference between the values
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM