将pandas DataFrame中的一列转换为带有nan值的float。

问题描述 投票:1回答:2

我正在使用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和Python3.4来处理数据。

python pandas python-3.4
2个回答
3
投票

你可以看到,如果你允许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

0
投票

在读取方法中添加转换参数--转换器={'TN':float,'TX':float}。

dfs[code] = pd.read_csv(path, sep = ';',converters={'TN':float,'TX':float}, index_col = 0, parse_dates = True, encoding = 'ISO-8859-1', dtype = float)
© www.soinside.com 2019 - 2024. All rights reserved.