Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Trying to keep the same type after saving a dataframe in a csv file

When I try to get my dataframe out of the csv file the type of the data changed. Is there a way I can avoid this?

example

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

CSVs are text files so don't inherently contain meta-data like datatypes.

When you're opening the CSV you've saved, Python/Pandas is interpreting what it thinks the datatypes are - presumably it's getting it slightly wrong compared to what you want (this is what's happening rather than your CSV being saved with the wrong datatypes).

Pandas 'read_csv' has a 'dtype' argument which will take a dictionary of column types. This should let you specify what data types you'd like. I'd suggest reading through the function documentation here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...