导出为CSV时,如何在列中保持前导零? [英] How can I keep leading zeros in a column, when I export to CSV?
问题描述
我正在尝试导出带有前导零的列的数据框,如下所示:
I am trying to export a dataframe with a column with leading zeros like this:
df["CD_LIN_NEG"]
0 001
1 001
2 004
3 001
4 001
5 001
6 003
7 006
Name: CD_LIN_NEG, dtype: object
但是当我导出到csv时,当我在Excel中打开文件时,所有前导零都会被截断.如何保持零?
But when I export to csv, all of the leading zeros are cut off any numbers when I open the file in Excel. How can I keep the zeros?
我试图转换为字符串,但不起作用:
I have tried to convert to string but it doesn't work:
df["CD_LIN_NEG"] = df['T_PROD_CP.LN'].astype(str).apply(lambda x: x.zfill(3))
或以这种方式:
df["CD_LIN_NEG"] = '00' + df['T_PROD_CP.LN'].astype(str)
推荐答案
这是@EdChum建议的excel问题.您需要使用apply('="{}".format)
将列包装在=""
中.这将告诉excel将条目视为返回引号内文本的公式.该文本将是您的值,且前导零.
This is an excel problem as @EdChum suggested. You'll want to wrap your column in =""
with apply('="{}".format)
. This will tell excel to treat the entry as a formula that returns the text within quotes. That text will be your values with leading zeros.
请考虑以下示例.
df = pd.DataFrame(dict(A=['001', '002']))
df.A = df.A.apply('="{}"'.format)
df.to_excel('test_leading_zeros.xlsx')
这篇关于导出为CSV时,如何在列中保持前导零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!