【问题标题】:how to get the int value from this $68.95 [closed]如何从此 $68.95 中获取 int 值 [关闭]
【发布时间】:2021-07-13 22:22:02
【问题描述】:

我试过了

int(df3.iloc[:,0:1].split('\'')[1])

它是这么说的

'DataFrame' object has no attribute 'split'.

我是熊猫的新手

【问题讨论】:

  • 结果究竟应该是什么?
  • 从 68.95 美元到 68.95 美元,应该是一个整数值
  • 68.95 不是整数...
  • ops ,我应该说只有68

标签: python pandas dataframe integer


【解决方案1】:

大概您希望对价格列中的每一行都执行此操作,而不仅仅是第一行(零索引)?在 pandas 中给猫剥皮的方法不止一种,但这样就可以解决问题。

import pandas as pd
pd.to_numeric(df3['price'].str.lstrip('$')).astype(int)

让我们根据评估的方式对其进行分解:

df3['price'] 返回一个系列对象:

0     $68.95
1    $157.49
Name: price, dtype: object

.str.lstrip('$') 对该系列中的每个项目调用字符串处理 lstrip 方法,从而返回一个删除了美元符号的新系列:

0     68.95
1    157.49
Name: price, dtype: object

将该新系列传递给pd.to_numeric(),它会返回另一个新系列,其中所有字符串都转换为float64:

0     68.95
1    157.49
Name: price, dtype: float64

最后.astype(int) 调用最后一个系列的astype 方法并将其转换为int32 dtype。

0     68
1    157
Name: price, dtype: int32

【讨论】:

  • 你让我清楚地了解了这一点。谢谢!!!!!!
【解决方案2】:

【讨论】:

    【解决方案3】:

    您在 cmets 中说您想要 68.95 作为整数。这是不可能的。你可以得到 68 作为整数与

    int(float(df.iloc[0,0].split('$')[1]))
    

    或者在浮点数转换后不转换为 int 为 68.95 的浮点数

    【讨论】:

    • 已更正!!在评论区
    【解决方案4】:

    获取 $price 字符串的数字部分并转换为浮点数(浮点数而不是整数,因为正如其他人所说,1.2 是浮点数而不是整数。我建议替换 '$' 而不是拆分它,以防价格有一个不带 $ 的数字。

    df3 = pd.DataFrame({'price': ['$68.95', '157.49']})
    df3['price_as_number'] = df3['price'].str.replace('$', '').astype(float)
    
    

    获取df3:

        price  price_as_number
    0  $68.95            68.95
    1  157.49           157.49
    

    【讨论】:

    • 成功了!!!!谢谢兄弟
    • 太好了,你能接受我的回答吗?
    猜你喜欢
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 2013-09-27
    • 1970-01-01
    • 2013-02-16
    • 2014-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多