Question: After pandas imports the csv file, some of the columns are empty, the column type is object format, and the cells in the column are in string format. Requirements: Convert empty columns (object) to floating point types (float)

# 读取文件
data = pd.read_csv("./data/data.csv", encoding='utf-8')
 
# 前两列丢掉
data = data.ix[:, 2:]
 
# 找到列名,转化为列表
col = list(data.columns)
 
# 把所有列的类型都转化为数值型,出错的地方填入NaN,再把NaN的地方补0
data[col] = data[col].apply(pd.to_numeric, errors='coerce').fillna(0.0)
# 至此,object的列(列中存储的是string类型)转成了float
 
# 最后一步,把所有列都转化成float类型,done!
data = pd.DataFrame(data, dtype='float')

Guess you like

Origin blog.csdn.net/gz153016/article/details/108889708