gpt4 book ai didi

python - 为什么 'na_values' 在 Pandas 中不能正常工作?

转载 作者:行者123 更新时间:2023-12-01 07:38:49 27 4
gpt4 key购买 nike

我正在阅读this file并将 -1 替换为 nan:

import pandas as pd
import os

path = "./data/"

filename = os.path.join(path,"SN_d_tot_V2.0.csv")
names = ['year', 'month', 'day', 'dec_year', 'sn_value' , 'sn_error', 'obs_num']
df = pd.read_csv(filename,sep=';',header=None,names=names,na_values=['-1'], index_col=False)

但替换仅适用于 sn_error 列(float64),不适用于 sn_value(int64) 。怎么了?如何替换所有-1值?

enter image description here

最佳答案

该列有前导空格,您需要在读取 CSV 时将其删除。

df = pd.read_csv('http://www.sidc.be/silso/INFO/sndtotcsv.php', 
sep=r'\s*;\s*',
engine='python',
header=None,
names=names,
na_values=[-1],
index_col=False)
df.head()

year month day dec_year sn_value sn_error obs_num
0 1818 1 1 1818.001 NaN NaN 0
1 1818 1 2 1818.004 NaN NaN 0
2 1818 1 3 1818.007 NaN NaN 0
3 1818 1 4 1818.010 NaN NaN 0
4 1818 1 5 1818.012 NaN NaN 0

关于python - 为什么 'na_values' 在 Pandas 中不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56825958/

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