如何从数据帧中保存CSV,以使数字中的零保留在列中? [英] How to save a CSV from dataframe, to keep zeros left in column with numbers?

查看:331
本文介绍了如何从数据帧中保存CSV,以使数字中的零保留在列中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python 3和熊猫中,我有一个数据框,其中包含带有代码的列 cpf

In Python 3 and pandas I have a dataframe with a column cpf with codes

candidatos_2014.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 26245 entries, 0 to 1063
Data columns (total 7 columns):
uf                 26245 non-null object
cargo              26245 non-null object
nome_completo      26245 non-null object
cpf                26245 non-null object
nome_urna          26245 non-null object
partido_eleicao    26245 non-null object
situacao           26245 non-null object
dtypes: object(7)
memory usage: 1.6+ MB

代码是这样的数字:"00229379273","84274662268","09681949153","53135636534" ...

The codes are numbers like these: "00229379273", "84274662268", "09681949153", "53135636534"...

我另存为CSV

candidatos_2014.to_csv('candidatos_2014.csv')

我使用Ubuntu和LibreOffice.但是,当我打开文件时, cpf 列未显示前导零:

I use Ubuntu and LibreOffice. But when I opened the file the cpf column does not show the leading zeros:

"229379273", "9681949153"

请问,有没有一种方法可以保存仅包含数字的列中的左侧保持零的CSV?

Please, is there a way to save a CSV that keeps zeros to the left in a column that only has numbers?

推荐答案

在读取csv文件时,将dtype指定为字符串,如下所示:

Specify dtype as string while reading the csv file as below:

# if you are reading data with leading zeros
candidatos_2014 = pd.read_csv('candidatos_2014.csv', dtype ='str')

或将数据列转换为字符串

or convert data column into string

# if data is generated in python you can convert column into string first
candidatos_2014['cpf'] = candidatos_2014['cpf'].astype('str')
candidatos_2014.to_csv('candidatos_2014.csv')

这篇关于如何从数据帧中保存CSV,以使数字中的零保留在列中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆