gpt4 book ai didi

python - 使用 pandas.read_csv 以空格作为千​​位分隔符读取 CSV 文件

转载 作者:行者123 更新时间:2023-11-28 21:39:40 27 4
gpt4 key购买 nike

我有一个如下所示的(法语)数据集:

time;col1;col2;col3
06.09.2017 05:30;329,02;5,7;259
06.09.2017 05:40;500,5;6,6;261
06.09.2017 05:50;521,73;6,7;266
06.09.2017 06:00;1 091,33;9,1;273
06.09.2017 06:10;1 262,43;10;285

我尝试使用以下命令读取它:

import pandas as pd
df=pd.read_csv("Example_dataset.csv",
index_col=0,
encoding='latin',
parse_dates=True,
dayfirst=True,
sep=';',
decimal=',',
thousands=' ')

col2 和 col3 被识别为 float 和整数,尽管 col1 不被识别为数字,因为其中有千位分隔符。有没有一种简单的方法来读取这个数据集?设置 thousands=' ' 似乎不起作用:

<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 5 entries, 2017-09-06 05:30:00 to 2017-09-06 06:10:00
Data columns (total 3 columns):
col1 5 non-null object
col2 5 non-null float64
col3 5 non-null int64
dtypes: float64(1), int64(1), object(1)
memory usage: 160.0+ bytes

有什么建议吗?

最佳答案

如果你有不间断的空格,我会建议使用 str.replace 的更积极的正则表达式:

df.col1 = df.col1.str.replace('[^\d.,e+-]', '')\
.str.replace(',', '.').astype(float)

正则表达式

[       # character group
^ # negation - ignore everything in this character group
\d # digit
. # dot
e # 'e' - exponent
+- # signs
]

关于python - 使用 pandas.read_csv 以空格作为千​​位分隔符读取 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46464462/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com