【问题标题】:Python add a leading zero to column with str and intPython 使用 str 和 int 在列中添加前导零
【发布时间】:2017-02-21 18:23:09
【问题描述】:

您好,我想用 str 和 int 在当前列中添加前导零,但我不知道如何操作。我只想在数字前添加前导零:不是 A111。数据是从 csv 文件导入的。我对熊猫和蟒蛇很陌生。

例如:

Section
1
2
3
4
4SS
15
S1
A111

转换成:

Section
01
02
03
04
4SS
15
S1
A111

【问题讨论】:

  • 您的数据是字符串吗?还是一排?
  • 这里的经验法则:发布一些示例代码或至少解释您正在使用的数据结构。那个打印输出没用。
  • 查看str.zfill()

标签: python pandas


【解决方案1】:

你可以使用str.zfill:

#numeric as string
df = pd.DataFrame({'Section':['1', '2', '3', '4', 'SS', '15', 'S1', 'A1']})

df['Section'] = df['Section'].str.zfill(2)
print (df)
  Section
0      01
1      02
2      03
3      04
4      SS
5      15
6      S1
7      A1

如果将numericstrings 混合,首先转换为string

df = pd.DataFrame({'Section':[1, 2, 3, 4, 'SS', 15, 'S1', 'A1']})

df['Section'] = df['Section'].astype(str).str.zfill(2)
print (df)
  Section
0      01
1      02
2      03
3      04
4      SS
5      15
6      S1
7      A1

【讨论】:

  • 谢谢!以为这篇文章由于某种原因被删除了
【解决方案2】:

试试这个

df['Section'] = df['Section'].apply(lambda x: x.zfill(2))

你得到

Section
0   01
1   02
2   03
3   04
4   SS
5   15
6   S1
7   A1

【讨论】:

  • @MaxU,对。 str.zfill() 比 apply 更可取
猜你喜欢
  • 2011-11-30
  • 2020-12-30
  • 2014-09-09
  • 2015-05-14
  • 2013-06-11
  • 1970-01-01
  • 2019-04-14
  • 2014-03-04
  • 1970-01-01
相关资源
最近更新 更多