【问题标题】:pd.read_feather problems with decimal / thousands separator and rounding problems for floatspd.read_feather 小数/千位分隔符问题和浮点数舍入问题
【发布时间】:2020-05-20 09:30:42
【问题描述】:

我想使用 .ftr 文件快速分析数百个表。不幸的是,我在使用小数和千位分隔符时遇到了一些问题,类似于 that post,只是 read_feather 不允许使用 decimal=',', thousands='.' 选项。我尝试了以下方法:

df['numberofx'] = (
    df['numberofx']
    .apply(lambda x: x.str.replace(".","", regex=True)
                      .str.replace(",",".", regex=True))

导致

AttributeError: 'str' object has no attribute 'str'

当我把它改成

df['numberofx'] = (
    df['numberofx']
    .apply(lambda x: x.replace(".","").replace(",","."))

我在结果中收到了一些奇怪的(四舍五入)错误,例如某些高于 1k 的数字是 22359999999999998 而不是 2236。 1k以下都是真实结果的10倍,这可能是因为删除了“。”浮点数并创建该数字的 int。

尝试

df['numberofx'] = df['numberofx'].str.replace('.', '', regex=True)

还会导致结果中出现一些奇怪的行为,因为一些数字在 10^12 中,而另一些则保持在 10^3 中。

Here is how I create my .ftr files from multiple Excel files。我知道我可以简单地从 Excel 文件创建 DataFrame,但这会大大降低我的日常计算速度。

我该如何解决这个问题?


编辑:问题似乎来自以 df 格式读取 excel 文件,该文件具有非美国标准的十进制和千位分隔符,而不是将其保存为羽毛。使用pd.read_excel(f, encoding='utf-8', decimal=',', thousands='.') 读取excel文件的选项解决了我的问题。这就引出了下一个问题:

为什么在羽毛文件中保存浮点数会导致奇怪的舍入错误,例如将 2.236 更改为 2.2359999999999998?

【问题讨论】:

  • 只是为了清楚您想在numberofx 列上将1.000.000,10 转换为1000000.10 吗?
  • 该列中的所有值都应该是整数。不知何故,这些值被存储为浮点数。我认为这个问题是因为欧洲与美国的 dezimal 符号。因此,所有大于 1k 的数字都将转换为例如2.236。我想收到原始整数值
  • 您确定数据框中的列包含float 而不是string 类型?对 ?查看列类型执行该行 --> df.dtypes['numberofx']
  • 你是对的,它存储为object,包括小数点和千位分隔符。

标签: python pandas rounding decimal-point feather


【解决方案1】:

您的代码中的问题是:

当您检查数据框 (Panda) 中的列类型时,您会发现:

df.dtypes['numberofx']

结果:输入object

所以建议的解决方案是尝试:

df['numberofx'] = df['numberofx'].apply(pd.to_numeric, errors='coerce')

解决此问题的另一种方法是将您的值转换为浮点数:

def coerce_to_float(val):
    try:
       return float(val)
    except ValueError:
       return val

df['numberofx']= df['numberofx'].applymap(lambda x: coerce_to_float(x))

为了避免这种类型的浮动“4.806105e+12”,这里有一个示例 示例

df = pd.DataFrame({'numberofx':['4806105017087','4806105017087','CN414149']})
print (df)
              ID
0  4806105017087
1  4806105017087
2       CN414149

print (pd.to_numeric(df['numberofx'], errors='coerce'))
0    4.806105e+12
1    4.806105e+12
2             NaN
Name: ID, dtype: float64

df['numberofx'] = pd.to_numeric(df['numberofx'], errors='coerce').fillna(0).astype(np.int64)
print (df['numberofx'])
              ID
0  4806105017087
1  4806105017087
2              0

【讨论】:

  • 谢谢@Zine Mahmoud!不幸的是,由于某些格式问题,所有应该高于 1k 并且有些浮动(例如 2.236)的数字都只是在该点之后被剪切(例如 2 而不是 2236)
【解决方案2】:

正如我在编辑中提到的,这里解决了我最初的问题:

path = r"pathname\*_somename*.xlsx"
file_list = glob.glob(path)
for f in file_list:
    df = pd.read_excel(f, encoding='utf-8', decimal=',', thousands='.')
    for col in df.columns:
            w= (df[[col]].applymap(type) != df[[col]].iloc[0].apply(type)).any(axis=1)
            if len(df[w]) > 0:

                df[col] = df[col].astype(str)

            if df[col].dtype == list:
                df[col] = df[col].astype(str)
    pathname = f[:-4] + "ftr"
    df.to_feather(pathname)
df.head()

我不得不添加decimal=',', thousands='.' 选项来读取excel 文件,我后来将其保存为羽毛。因此,在使用 .ftr 文件时并没有出现问题,而是在之前。舍入问题似乎来自将具有不同小数和千位分隔符的数字保存为 .ftr 文件。

【讨论】:

    猜你喜欢
    • 2022-07-01
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    • 1970-01-01
    • 2010-09-22
    • 2021-09-14
    • 2017-10-17
    • 1970-01-01
    相关资源
    最近更新 更多