如何Pandas重命名列名并在记录前加上0?
How to Pandas renaming column names and prepend 0's to record?
这只是我编写的 DataFrame 示例。我已经输出了我希望看到的方式。我想在这里实现两件事。
- 将列名称中的句点
.
替换为 _
下划线。我可以
单独执行此操作,但我想循环执行此操作,就像我们假设
有 40-50 个列名。
- 检查
Car.Mile
是否为记录中的 5 位数字。如果不预置 0's
car.Model car.Color car.Year car.Mile
0 AUDI RED 2015 14000
1 BUIC WHITE 2015 9000
2 PORS BLUE 2016 7000
3 HONDA BLACK 2015 100000
输出
car_Model car_Color car_Year car_Mile
0 AUDI RED 2015 014000
1 BUIC WHITE 2015 009000
2 PORS BLUE 2016 007000
3 HONDA BLACK 2015 100000
您可以使用 str.replace
for replacing .
Then convert column car_Mile
to string by astype
and last apply
zfill
:
df.columns = df.columns.str.replace('.', '_')
df['car_Mile'] = df['car_Mile'].astype(str).apply(lambda x: x.zfill(6))
print df
car_Model car_Color car_Year car_Mile
0 AUDI RED 2015 014000
1 BUIC WHITE 2015 009000
2 PORS BLUE 2016 007000
3 HONDA BLACK 2015 100000
或者:
df.columns = df.columns.str.replace('.', '_')
df['car_Mile'] = df['car_Mile'].astype(str).apply(lambda x: '{0:0>6}'.format(x))
print df
car_Model car_Color car_Year car_Mile
0 AUDI RED 2015 014000
1 BUIC WHITE 2015 009000
2 PORS BLUE 2016 007000
3 HONDA BLACK 2015 100000
编辑:
谢谢 for improvement - apply
is not necessary, better is use str.zfill
:
df.columns = df.columns.str.replace('.', '_')
df['car_Mile'] = df['car_Mile'].astype(str).str.zfill(6)
print df
car_Model car_Color car_Year car_Mile
0 AUDI RED 2015 014000
1 BUIC WHITE 2015 009000
2 PORS BLUE 2016 007000
3 HONDA BLACK 2015 100000
这只是我编写的 DataFrame 示例。我已经输出了我希望看到的方式。我想在这里实现两件事。
- 将列名称中的句点
.
替换为_
下划线。我可以 单独执行此操作,但我想循环执行此操作,就像我们假设 有 40-50 个列名。 - 检查
Car.Mile
是否为记录中的 5 位数字。如果不预置 0's
car.Model car.Color car.Year car.Mile
0 AUDI RED 2015 14000
1 BUIC WHITE 2015 9000
2 PORS BLUE 2016 7000
3 HONDA BLACK 2015 100000
输出
car_Model car_Color car_Year car_Mile
0 AUDI RED 2015 014000
1 BUIC WHITE 2015 009000
2 PORS BLUE 2016 007000
3 HONDA BLACK 2015 100000
您可以使用 str.replace
for replacing .
Then convert column car_Mile
to string by astype
and last apply
zfill
:
df.columns = df.columns.str.replace('.', '_')
df['car_Mile'] = df['car_Mile'].astype(str).apply(lambda x: x.zfill(6))
print df
car_Model car_Color car_Year car_Mile
0 AUDI RED 2015 014000
1 BUIC WHITE 2015 009000
2 PORS BLUE 2016 007000
3 HONDA BLACK 2015 100000
或者:
df.columns = df.columns.str.replace('.', '_')
df['car_Mile'] = df['car_Mile'].astype(str).apply(lambda x: '{0:0>6}'.format(x))
print df
car_Model car_Color car_Year car_Mile
0 AUDI RED 2015 014000
1 BUIC WHITE 2015 009000
2 PORS BLUE 2016 007000
3 HONDA BLACK 2015 100000
编辑:
谢谢apply
is not necessary, better is use str.zfill
:
df.columns = df.columns.str.replace('.', '_')
df['car_Mile'] = df['car_Mile'].astype(str).str.zfill(6)
print df
car_Model car_Color car_Year car_Mile
0 AUDI RED 2015 014000
1 BUIC WHITE 2015 009000
2 PORS BLUE 2016 007000
3 HONDA BLACK 2015 100000