【问题标题】:Extract a particular value from categorical column using Python使用 Python 从分类列中提取特定值
【发布时间】:2020-12-22 06:57:11
【问题描述】:

以下是包含银行客户交易数据的示例表。我需要创建一个单独的列作为客户的年薪,从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

注意:交易数据为三个月。因此,工资在此表中三次记入特定客户的帐户,为期三个月。

(Dr = 借方交易,Cr = 贷方交易)

【问题讨论】:

  • 从三个月的数据来看taking annual salary of customer背后的逻辑是什么?这个Since the transaction data is of three months the customer ID will not be unique. 是什么意思?
  • 一位客户将一些金额作为工资记入他的帐户。我们需要根据这些数据计算他的年薪......
  • 太棒了。当我们有 3 个月而不是 1 个月的工资数据时怎么样...检查编辑...
  • 在这种情况下,您必须按月份和客户进行过滤。即,整个过滤后的数据框在三个月中只有一个条目。我的建议是,这样做,df.sort(["Customer_ID", "Date"])df.drop_duplicates(subset=["Customer_ID", "Date"], keep='first')。这将具有上述条件。
  • 排序后我应该继续 df[df["txn_description"]=="SALARY"] df["Annual"] = df["Amount"]*12

标签: python pandas data-science data-analysis


【解决方案1】:

你可以试试这个,

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

此外,如果你想将它应用到原始框架上找到这个,

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

并使用 df.map(dic) 将其应用于实际的 dtaframe

解释:

  1. 首先删除不需要的记录,只获取“cr”或 Salary 记录。
  2. 现在Dataframe有每个客户一个月数据的工资贷记记录。即,客户 ID 和金额是一对一的映射。
  3. 金额乘以 12 得到年值。
  4. 将客户转换为 dic 中的年值并替换为实际框架。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2011-12-13
    • 1970-01-01
    • 1970-01-01
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多