如果Pandas DataFrame的某列中的值达到指定长度,就在该值后面添加一个字符
我正在尝试重新格式化数据框中某个人身高列的值,例如把5'8" 转换为5 Feet 8 Inches,我想我至少可以先把单引号和双引号替换成 " Feet" 和 " Inches"。所以,我有这个可以正常完成替换的示例:
df['Height'] = df['Height'].str.replace("'", ' Feet ').str[:-1] + " Inches"
我遇到的问题是,格式还需要是 "... 0x Inches",例如 "5 Feet 08 Inches"。我猜可以根据数值的长度来实现,但我还不知道怎么写。如果我的计算没错,这里某处的if的流程图应该是:
if Height field value length = 15 then replace add "0" in the 8th position else do nothing to the value
我很乐意尝试几种不同的选项,下面是我尝试的结果。
df['Height'] = np.where(df.Height.str.len() == 15, df.Height, df.Height[:8] + '0' + df.Height[8:])
No change
df['Height'] = np.where(df['Height'].str.len() == 15, df.apply(lambda x: x['Height'][:8]+'0'+x['Height'][8:], axis=1), df['Height'])
TypeError: 'float' object is not subscriptable
df['Height'] = np.where(df['Height'].str.len() == 15, df['Height'], df['Height'][:8] + '0' + df['Height'][8:])
No change
谢谢!
解决方案
我认为你需要的是下面这个。它使用正则表达式来捕捉英尺和英寸的数字,并用一个辅助函数来格式化:
import pandas as pd
def fmt(m):
f = int(m.group(1))
i = int(m.group(2))
return f'{f} Feet {i:02} Inches'
df = pd.DataFrame(('5\'8"', '6\'2"', '5\'10"'), columns=('Height',))
print(df)
print()
df['Height'] = df['Height'].str.replace(r'(\d+)\'(\d+)"', fmt, regex=True)
print(df)
输出:
Height
0 5'8"
1 6'2"
2 5'10"
Height
0 5 Feet 08 Inches
1 6 Feet 02 Inches
2 5 Feet 10 Inches
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。