保存 pandas 数据框,但保留NA值 [英] Save pandas dataframe but conserving NA values
本文介绍了保存 pandas 数据框,但保留NA值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个代码
import pandas as pd
import numpy as np
import csv
df = pd.DataFrame({'animal': 'cat dog cat fish dog cat cat'.split(),
'size': list('SSMMMLL'),
'weight': [8, 10, 11, 1, 20, 12, 12],
'adult' : [False] * 5 + [True] * 2});
然后我用NA值更改了权重:
And I changed the weight with NA values:
df['weight'] = np.nan
最后我保存了它
df.to_csv("ejemplo.csv", sep=";", decimal=",", quoting=csv.QUOTE_NONNUMERIC, index=False)
但是,当我读取文件时,我使用的是",而不是NA 我想用NA代替Nan
But when I read the file I have "", instead of NA I want to put NA instead of Nan
我想要作为输出:
adult;animal;size;weight
False;"dog";"S";NA
False;"cat";"M";NA
推荐答案
要获得该特定输出,您必须显式传递引号.
To get that specific output, you'll have to pass the quotes in explicitly.
df = pd.DataFrame({'animal': r'"cat" "dog" "cat" "fish" "dog" "cat" "cat"'.split(),
'size': list(r'"S" "S" "M" "M" "M" "L" "L"'.split()),
'weight': [8, 10, 11, 1, 20, 12, 12],
'adult' : [False] * 5 + [True] * 2});
df['weight'] = '%s' %('NA')
df.to_csv("ejemplo.csv", sep=';', decimal=',',quoting=csv.QUOTE_NONE, index=False)
这篇关于保存 pandas 数据框,但保留NA值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文