简体   繁体   English

在 dataframe 中,如何根据另一列的条件在另一列中写入字符串

[英]In a dataframe, how to write a string in one column based on conditions in another

I have an accounting trial balance (tb) in excel that I loaded as a df in python.我在 excel 中有一个会计试算表 (tb),我在 python 中将其作为 df 加载。 The df has an index column on the left, starting with 0. column 1 is the account name, column 2 are the debits, and column 3 are the credits. df 左侧有一个索引列,从 0 开始。第 1 列是帐户名称,第 2 列是借方,第 3 列是贷方。 Each row is an account with either a debit or credit balance.每行是一个具有借方或贷方余额的帐户。 The tb has a "totals" row at the end, with the totals for debits and credits in columns 2 and 3. The debit and credit totals equal each other. tb 的末尾有一个“总计”行,第 2 列和第 3 列中有借方和贷方的总计。借方和贷方总计彼此相等。

I would like to create a new "account #" column and give each account a number.我想创建一个新的“帐户编号”列并给每个帐户一个编号。 These numbers should be from 1 to however many accounts there are, up to and not including the totals row.这些数字应该是从 1 到有多少帐户,最多不包括总计行。 The account # in the totals row should be blank.总计行中的帐户编号应为空白。

I wrote the following for loop, but it continues to assign an account number in the totals row:我编写了以下 for 循环,但它继续在总计行中分配一个帐号:

for i in df['Account']:
    if i == 'TOTAL':
        df['account #'] == ''
    else:
        df['account #'] = df.index + 1

What can I do to have the account # for "totals" be blank?我该怎么做才能让“总计”的帐户 # 为空白?

We can do我们可以做的

import numpy as np 

df['account #']=np.where(df['Account']=='TOTAL', '' , df.index+1) 

暂无
暂无

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

相关问题 如何根据另一个 dataframe 的条件过滤一个 dataframe 中列的特定值? - How do you filter on specific values of a column in one dataframe based on conditions of another dataframe? 如何根据pythons dataframe中的条件将值从一列复制到另一列? - How to copy value from one column to another based on conditions in pythons dataframe? 根据条件将值从一列到另一列熊猫数据框中 - Give values from one column to another column in pandas dataframe based on conditions 如何根据 Pandas Dataframe 中的另一列对一列进行排序? - How to sort one column based on another column in Pandas Dataframe? 如何在一个 Pandas 数据帧列中搜索字符串作为另一个数据帧中的子字符串 - How to search a string in one pandas dataframe column as a substring in another dataframe 基于Python中的多个条件将来自多个数据帧的一列合并到另一个数据帧 - Merge one column from multiple dataframes to another dataframe based on multiple conditions in Python 根据另一个 dataframe 的条件乘以整个 dataframe 列 - Multiply an entire dataframe column based on conditions from another dataframe 如何根据另一个数据框的条件创建新的数据框列? - How do I create a new dataframe column based on conditions of another dataframe? 根据包含字符串的列(2 个定义的条件)从另一个数据帧创建 dataframe - Create a dataframe from another data frame based on column containing string (2 defined conditions) 在某些条件下,如何根据不同的数据框列替换一个数据框的列值? - How can we replace the columns values of one dataframe based on different dataframe column using some conditions?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM