我正在尝试根据我的Dataframe中的2列来填充。第一列称为单位,它只包含两个字符串,“公制”和“帝国”。
第二列称为“关闭”,其中包含大量的数字。然而,如果Colum是公制的,我需要将数字填充到5,如果它是皇家的,我需要填充到4。例如:公制: 23需要变成00023。帝国: 23需要变成0023
基本上,如果第一列(单位)=米制,那么我想看第二栏(关闭),如果第一列(单位)=帝国a,我想看第二列(关闭)和z填充到5,然后我想看第二列(关闭)和填充到4。
这是当前的代码,但是我得到了错误:“函数”对象没有属性'astype‘
df['Unit'] == 'Metric', df['closing'].replace.astype(str).zfill(5)
df['Unit'] == 'Imperial', df['closing'].replace.astype(str).zfill(4)发布于 2021-09-19 16:23:59
考虑到您只有两个选择(Metric,Imperial)可供选择,您可以使用Numpy where。
输入sample.csv
Unit closing
0 Imperial 20
1 Metric 284
2 Imperial 1451
3 Imperial 45
4 Metric 8491import pandas as pd
import numpy as np
df = pd.read_csv('sample.csv')
df['closing'] = np.where(df['Unit'] == 'Metric',
df['closing'].astype(str).str.zfill(5),
df['closing'].astype(str).str.zfill(4),
)
print(df)df输出
Unit closing
0 Imperial 0020
1 Metric 00284
2 Imperial 1451
3 Imperial 0045
4 Metric 08491https://stackoverflow.com/questions/69224921
复制相似问题