【问题标题】:List comprehension showing numbers in a weird format列表理解以奇怪的格式显示数字
【发布时间】:2022-01-10 17:17:47
【问题描述】:

我有一个这样的熊猫数据框:

Transaction Transaction Amount
Deposit 10.00
Dividend 0.9
Taxes 0.04

我正在应用这样的列表理解:

df['Tax'] = ['0' if i == "Deposit" or i == "Dividend" else df['Transaction Amount'] for i in df['Transaction']]


df['Net Amount'] = [df['Transaction Amount'] if i == "Deposit" or i == "Dividend" else -1 * df['Tax'] for i in df['Transaction']]

但是,对于这两种情况,我都会得到如下奇怪的输出:“0 1.00 1 1000.00 2 1000.00 3...”

Transaction Amount 是一个 float64,我尝试将其设为字符串,看看是否能解决问题,但我一直得到相同的结果。

【问题讨论】:

  • 请您提供一个包含您期望的输出的数据框吗?
  • 伙计,'0' 是一个字符串。

标签: python pandas dataframe list-comprehension


【解决方案1】:

尝试使用 np.where 而不是列表理解。

import numpy as np
df['Tax'] = np.where(df['Transaction'].isin(['Deposit', 'Dividend']),
                     0 ,df['Transaction Amount'])

df['Net Amount'] = np.where(df['Transaction'].isin(['Deposit', 'Dividend']), 
                            df['Transaction Amount'], -1*df['Tax'])

输出:

  Transaction  Transaction Amount   Tax  Net Amount
0     Deposit               10.00  0.00       10.00
1    Dividend                0.90  0.00        0.90
2       Taxes                0.04  0.04       -0.04

【讨论】:

    猜你喜欢
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多