【问题标题】:Pandas: convert column (price data) to integerPandas:将列(价格数据)转换为整数
【发布时间】:2021-05-29 04:12:23
【问题描述】:

我写了一个函数,它的目的是将价格数据从美元转换为整数。很简单。

每个条目上的数据格式如下所示(通过示例):$40.00、$1,100.00 等

注意:值得一提的是,在我进行任何astype() 更改之前,dtype 最初是一个对象。

def convert_price(df):
    df['price'] = df['price'].str.replace('$', '') 
    df['price'] = df['price'].str.replace(',', '') # these two lines remove unwanted symbols. Leaving me with a '1100.00' for example
    df['price'] = df['price'].astype('Int64') # convert data to int. 
    return df

我收到一个错误:无法将对象转换为 IntegerDtype。

我尝试解决它,如之前在 SoF 问题中提到的那样,首先转换为浮点数,然后转换为整数:

def convert_price(df):
    df['price'] = df['price'].str.replace('$', '')
    df['price'] = df['price'].str.replace(',', '')
    df['price'] = df['price'].astype('float')
    df['price'] = df['price'].astype('Int64')
    return df

新错误:无法安全地将非等效 float64 转换为 int64

然后我搜索了潜在的缺失值:

df[['price']].isna().sum()
output:
price    0
dtype: int64

没有找到,但尽管我得到了错误, 检查系列的 dtype 会返回“int64”。

谁能向我解释这里到底发生了什么。在调用我的函数来表达它时,我得到了错误,如上所述。但是输出似乎给出了我想要的结果?

编辑:小数据样本

【问题讨论】:

  • 您是否也尝试过删除点(“.”)?
  • 请添加您的约会样例
  • 我做到了,是的。我的想法是删除“。”然后除以 100。但我收到一个错误。

标签: python pandas


【解决方案1】:

可能有一些值,例如 "$12.34",无法直接转换为 int64。

所以我建议您向上或向下转换每个数字。而向上转型可以通过round(decimals=FLOAT_POINT_SIZE)解决。

这是一个向上转换的示例代码。

import pandas as pd

df = pd.DataFrame({"price": ['$40.00', '$1,100.00', '$12.34']})

df['price'] = df['price'].str.replace('$', '')
df['price'] = df['price'].str.replace(',', '')
df['price'] = df['price'].astype('float')

# ------- Added -------
df = df.round(decimals=0)
# ---------------------

df['price'] = df['price'].astype('Int64')

如果你看到df

price
0 40
1 1100
2 12

【讨论】:

  • 你的意思是斯塔克。似乎这已经成功了。我会仔细检查 df 看看是否一切正常
  • @DropKick Up/down-casting 如果某些数据有浮点数可能需要 :)
【解决方案2】:

这段代码对我来说很好用。我只是使用了 float() 和 int() 而不是您使用的 astype() 方法。

import pandas as pd

def convert_price(df):
   df['price'] = df['price'].replace('$', '')
    df['price'] = df['price'].replace(',', '')
    df['price'] = float(df['price'])
    df['price'] = int(df['price'])
    return df

data = {
  "price": "$1,100.00"
}

df = pd.DataFrame(data, index = ["price"])
print(convert_price(df['price']))

【讨论】:

  • 感谢您的建议,但是我收到以下错误:TypeError: cannot convert the series to
【解决方案3】:

您的代码很好,如果您只是将 astype("Int64") 更改为 astype("int64")(没有大写 I),那么它正在运行!

import pandas as pd
data = {"price" : ["$40.00", "1,000.00"]}
df_data = pd.DataFrame(data)

df_data.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 2 entries, 0 to 1
Data columns (total 1 columns):
 #   Column  Non-Null Count  Dtype 
---  ------  --------------  ----- 
 0   price   2 non-null      object
dtypes: object(1)
memory usage: 144.0+ bytes

def convert_price(df):
df['price'] = df['price'].str.replace('$', '')
df['price'] = df['price'].str.replace(',', '')
df['price'] = df['price'].astype('float')
df['price'] = df['price'].astype('int64') # without capital I
return df

convert_price(df_data) 

df_data.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 2 entries, 0 to 1
Data columns (total 1 columns):
 #   Column  Non-Null Count  Dtype
---  ------  --------------  -----
 0   price   2 non-null      int64
dtypes: int64(1)
memory usage: 144.0 bytes

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-15
    • 2018-03-25
    • 1970-01-01
    • 2023-04-08
    • 2017-06-22
    • 1970-01-01
    • 1970-01-01
    • 2018-01-18
    相关资源
    最近更新 更多