简体   繁体   English

使用 Python 从分类列中提取特定值

[英]Extract a particular value from categorical column using Python

Following is the sample table which consists of transaction data of bank customers.以下是由银行客户的交易数据组成的示例表。 I need to create a separate column as annual salary of customer taking the data from txn_description column.我需要创建一个单独的列作为客户的年薪,从txn_description列中获取数据。

Customer_ID txn_description Amount Type
01           POS            345    Dr
02           SALARY         2000   Cr
03           INTER BANK     148    Dr
04           SALARY         1500   Cr
05           NEFT           289    Dr
06           SALARY         1800   Cr
01           NEFT           40     Dr
02           SALARY         2000   Cr
04           POS            69     Dr
04           SALARY         1500   Cr
06           SALARY         1800   Cr

Note: The transaction data is of three months.注:交易数据为三个月。 So the salary is credited to a particular customer's account thrice in this table for three months.因此,在三个月内,工资在此表中三次记入特定客户的帐户。

(Dr = Debit transaction and Cr = Credit transaction) (Dr = 借方交易,Cr = 贷方交易)

you could try this,你可以试试这个

df= df[df["txn_description"]=="SALARY"]
df["Annual"] = df["Amount"]*12

O/P:开/关:

   Customer_ID txn_description  Amount  Annual
1            2          SALARY    2000   24000
3            4          SALARY    1500   18000
5            6          SALARY    1800   21600

Furthermore, If you want to apply it on original frame find this,此外,如果您想将其应用于原始框架,请找到这个,

dic = df.set_index("Customer_ID")["Annual"].to_dict()

and apply it to actual dtaframe using df.map(dic)并使用df.map(dic)将其应用于实际的 dtaframe

Explanation:解释:

  1. First remove unwanted records, get only 'cr' or Salary records.首先删除不需要的记录,只获取 'cr' 或 Salary 记录。
  2. Now Dataframe has salary credited record of a month data of each customer.现在Dataframe有每个客户一个月的工资数据记录。 ie, customer id and amount is one to one map.即,客户 ID 和金额是一对一的映射。
  3. multiply amount with 12 to get annual value.将金额乘以 12 得到年值。
  4. convert customer to annual value in dic and replace into actual frame.将客户转换为 dic 中的年度价值并替换为实际框架。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM