将 pandas DataFrame 中的列转换为具有 nan 值的浮点数

Convert a column from a pandas DataFrame to float with nan values

我正在使用 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)

这个returns,随心所欲

RR     object
TN    float64
TX    float64
dtype: object

在读取方法中添加转换参数 - converters={'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)