TiT*_*iTo 6 python decimal-point rounding pandas feather
我想使用 .ftr 文件来快速分析数百个表。不幸的是,我在十进制和千位分隔符方面遇到了一些问题,类似于那个帖子,只是 read_feather 不允许decimal=',', thousands='.'选项。我尝试了以下方法:
df['numberofx'] = (
df['numberofx']
.apply(lambda x: x.str.replace(".","", regex=True)
.str.replace(",",".", regex=True))
Run Code Online (Sandbox Code Playgroud)
导致
AttributeError: 'str' object has no attribute 'str'
Run Code Online (Sandbox Code Playgroud)
当我把它改成
df['numberofx'] = (
df['numberofx']
.apply(lambda x: x.replace(".","").replace(",","."))
Run Code Online (Sandbox Code Playgroud)
我在结果中收到一些奇怪的(四舍五入)错误,例如 22359999999999998 而不是 2236 对于某些高于 1k 的数字。所有低于 1k 的都是真实结果的 10 倍,这可能是因为删除了“.”。的浮点数并创建该数字的 int。
试
df['numberofx'] = df['numberofx'].str.replace('.', '', regex=True)
Run Code Online (Sandbox Code Playgroud)
也会导致结果中出现一些奇怪的行为,因为有些数字在 10^12 中,而其他数字则应保持在 10^3 中。
下面是我如何从多个 Excel 文件创建我的 .ftr 文件。我知道我可以简单地从 Excel 文件创建数据帧,但这会大大减慢我的日常计算速度。
我该如何解决这个问题?
编辑:这个问题似乎来自于将 excel 文件作为非美国标准的关于十进制和千位分隔符的 df 读取,而不是将其保存为羽毛。使用pd.read_excel(f, encoding='utf-8', decimal=',', thousands='.')读取 excel 文件的选项解决了我的问题。这就引出了下一个问题:
为什么在羽毛文件中保存浮点数会导致奇怪的舍入错误,例如将 2.236 更改为 2.2359999999999998?
正如我在编辑中提到的,这解决了我最初的问题:
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()
Run Code Online (Sandbox Code Playgroud)
我必须添加decimal=',', thousands='.'在 Excel 文件中读取的选项,后来我将其保存为 Feather。因此,问题不是在使用 .ftr 文件时出现的,而是在之前出现的。舍入问题似乎来自将具有不同小数和千位分隔符的数字保存为 .ftr 文件。
| 归档时间: |
|
| 查看次数: |
248 次 |
| 最近记录: |