Python 在 Pandas Dataframe 中为字符串添加前导零

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23836277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:30:18  来源:igfitidea点击:

Add Leading Zeros to Strings in Pandas Dataframe

pythonstringpandas

提问by jgaw

I have a pandas data frame where the first 3 columns are strings:

我有一个熊猫数据框,其中前 3 列是字符串:

         ID        text1    text 2
0       2345656     blah      blah
1          3456     blah      blah
2        541304     blah      blah        
3        201306       hi      blah        
4   12313201308    hello      blah         

I want to add leading zeros to the ID:

我想在 ID 中添加前导零:

                ID    text1    text 2
0  000000002345656     blah      blah
1  000000000003456     blah      blah
2  000000000541304     blah      blah        
3  000000000201306       hi      blah        
4  000012313201308    hello      blah 

I have tried:

我试过了:

df['ID'] = df.ID.zfill(15)
df['ID'] = '{0:0>15}'.format(df['ID'])

采纳答案by Rohit

Try:

尝试:

df['ID'] = df['ID'].apply(lambda x: '{0:0>15}'.format(x))

or even

甚至

df['ID'] = df['ID'].apply(lambda x: x.zfill(15))

回答by Guangyang Li

strattribute contains most of the methods in string.

str属性包含字符串中的大多数方法。

df['ID'] = df['ID'].str.zfill(15)

See more: http://pandas.pydata.org/pandas-docs/stable/text.html

查看更多:http: //pandas.pydata.org/pandas-docs/stable/text.html

回答by Daniil Mashkin

It can be achieved with a single line while initialization. Just use convertersargument.

它可以在初始化时用一行来实现。只需使用转换器参数。

df = pd.read_excel('filename.xlsx', converters={'ID': '{:0>15}'.format})

so you'll reduce the code length by half :)

所以你会减少一半的代码长度:)

PS: read_csvhave this argument as well.

PS:read_csv也有这个说法。

回答by jpp

With Python 3.6+, you can also use f-strings:

在 Python 3.6+ 中,您还可以使用 f 字符串:

df['ID'] = df['ID'].map(lambda x: f'{x:0>15}')

Performance is comparable or slightly worse versus df['ID'].map('{:0>15}'.format). On the other hand, f-strings permit more complex output, and you can use them more efficiently via a list comprehension.

性能与df['ID'].map('{:0>15}'.format). 另一方面,f 字符串允许更复杂的输出,您可以通过列表推导更有效地使用它们。

Performance benchmarking

性能基准测试

# Python 3.6.0, Pandas 0.19.2

df = pd.concat([df]*1000)

%timeit df['ID'].map('{:0>15}'.format)                  # 4.06 ms per loop
%timeit df['ID'].map(lambda x: f'{x:0>15}')             # 5.46 ms per loop
%timeit df['ID'].astype(str).str.zfill(15)              # 18.6 ms per loop

%timeit list(map('{:0>15}'.format, df['ID'].values))    # 7.91 ms per loop
%timeit ['{:0>15}'.format(x) for x in df['ID'].values]  # 7.63 ms per loop
%timeit [f'{x:0>15}' for x in df['ID'].values]          # 4.87 ms per loop
%timeit [str(x).zfill(15) for x in df['ID'].values]     # 21.2 ms per loop

# check results are the same
x = df['ID'].map('{:0>15}'.format)
y = df['ID'].map(lambda x: f'{x:0>15}')
z = df['ID'].astype(str).str.zfill(15)

assert (x == y).all() and (x == z).all()

回答by Deskjokey

If you are encountering the error:

如果您遇到错误:

Pandas error: Can only use .str accessor with string values, which use np.object_ dtype in pandas

Pandas 错误:只能使用带有字符串值的 .str 访问器,它在 Pandas 中使用 np.object_ dtype

df['ID'] = df['ID'].astype(str).str.zfill(15)