我正在使用 Pandas 和 Python3.4 操作数据。我遇到了特定 csv 文件的问题。我不知道为什么,即使有nan
值,pandas 通常也会将列读取为float
. 在这里它将它们读作string
. 这是我的 csv 文件的样子:
Date RR TN TX
08/10/2015 0 10.5 19.5
09/10/2015 0 5.5 20
10/10/2015 0 5 24
11/10/2015 0.5 7 24.5
12/10/2015 3 12 23
...
27/04/2017
28/04/2017
29/04/2017
30/04/2017
01/05/2017
02/05/2017
03/05/2017
04/05/2017
问题是我无法将其转换为float
因为nan
最后的值。我需要它们,float
因为我正在尝试做TN
+ TX
。这是我到目前为止尝试过的:
读取文件时:
dfs[code] = pd.read_csv(path, sep = ';', index_col = 0, parse_dates = True, encoding = 'ISO-8859-1', dtype = float)
我也试过:
dtype = {
'TN': np.float,
'TX': np.float
}
dfs[code] = pd.read_csv(path, sep = ';', index_col = 0, parse_dates = True, encoding = 'ISO-8859-1', dtype = dtype)
否则,此时执行添加我也尝试过:
tn = dfs[code]['TN'].astype(float)
tx = dfs[code]['TX'].astype(float)
formatted_dfs[code] = tn + tx
但我总是得到同样的错误:
ValueError: could not convert string to float.
我知道我可以逐行进行,测试值是否为nan
,但我很确定有更简单的方法。你知道怎么做吗?还是我必须一行一行地做?谢谢。
你可以看到,如果你允许 pandas 自己检测 dtypes,你就避免了 ValueError 并发现了潜在的问题。
In [4]: df = pd.read_csv(path, sep=';', index_col=0, parse_dates=True, low_memory=False)
In [5]: df
Out[5]:
Empty DataFrame
Columns: []
Index: [08/10/2015 0 10.5 19.5, 09/10/2015 0 5.5 20, 10/10/2015 0 5 24, 11/10/2015 0.5 7 24.5, 12/10/2015 3 12 23, 27/04/2017 , 28/04/2017 , 29/04/2017 , 30/04/2017 , 01/05/2017 , 02/05/2017 , 03/05/2017 , 04/05/2017 ]
似乎您';'
无意中指定了分隔符,因为您的文件是用空格分隔的。由于没有任何分号,整个行都被读入索引。
首先,尝试使用正确的分隔符读入您的文件
df = pd.read_csv(path, delim_whitespace=True, index_col=0, parse_dates=True, low_memory=False)
现在,某些行的数据不完整。从概念上讲,一个简单的解决方案是尝试将值转换为np.float
,并用np.nan
其他方式替换它们。
def f(x):
try:
return np.float(x)
except:
return np.nan
df["TN"] = df["TN"].apply(f)
df["TX"] = df["TX"].apply(f)
print(df.dtypes)
这会根据需要返回
RR object
TN float64
TX float64
dtype: object
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句