Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

python - Save pandas dataframe but conserving NA values

I have this code

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}); 

And I changed the weight with NA values:

df['weight'] = np.nan

And finally I saved it

df.to_csv("ejemplo.csv", sep=";", decimal=",", quoting=csv.QUOTE_NONNUMERIC, index=False)

But when I read the file I have "", instead of NA I want to put NA instead of Nan

I want as output:

adult;animal;size;weight
False;"dog";"S";NA
False;"cat";"M";NA    
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want a string to represent NaN values then pass na_rep to to_csv:

In [8]:
df.to_csv(na_rep='NA')

Out[8]:
',adult,animal,size,weight
0,False,cat,S,NA
1,False,dog,S,NA
2,False,cat,M,NA
3,False,fish,M,NA
4,False,dog,M,NA
5,True,cat,L,NA
6,True,cat,L,NA
'

If you want the NA in quotes then escape the quotes:

In [3]:
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})
df['weight'] = np.NaN
df.to_csv(na_rep=''NA'')

Out[3]:
",adult,animal,size,weight
0,False,cat,S,'NA'
1,False,dog,S,'NA'
2,False,cat,M,'NA'
3,False,fish,M,'NA'
4,False,dog,M,'NA'
5,True,cat,L,'NA'
6,True,cat,L,'NA'
"

EDIT

To get the desired output use these params:

In [27]:
df.to_csv(na_rep='NA', sep=';', index=False,quoting=3)
?
Out[27]:
'adult;animal;size;weight
False;cat;S;NA
False;dog;S;NA
False;cat;M;NA
False;fish;M;NA
False;dog;M;NA
True;cat;L;NA
True;cat;L;NA
'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...