我觉得你的伙伴,我有同样的问题。 但值得庆幸的是这不是那么难
import pandas as pd
df = pd.DataFrame({'height': [16, 7, '6m', '2.4', '3,5', 'Asdf', '9;6;3']})
df['height'] = df['height'].astype(str) # force type str
df['height'] = df['height'].str.replace('.', ',', regex=False) # . -> ,
df['height'] = df['height'].str.replace('[A-Za-z]', '') # remove all characters (regex)
df['height'] = df['height'].str.split(';').apply(max) # pick largest value from 9;6;3
df['height'] = pd.to_numeric(df['height'], errors='coerce') # force float
你会得到
height
0 16.0
1 7.0
2 6.0
3 2.4
4 3.5
5 NaN
6 9.0
现在,如果你想把你的脚米(我是默认的假设是米),则需要增加一个级别的肤色
import pandas as pd
import numpy as np
import re
def feet_to_m(s):
if '\'' in s or "\"" in s:
if '\'' in s:
feet = float(s.split('\'')[0])
else:
feet = 0
if '\"' in s:
if '\'' in s:
inch = float(s.split('\'')[1].split('\"')[0])
else:
inch = float(s.split('\"')[0])
else:
inch = 0
return (feet*12 + inch) * 0.0254
else:
return s
df = pd.DataFrame({'height': [16, 7, '6m', '2.4', '3,5', 'Asdf', '9;6;3', "11' 4\"", "4'", "15\""]})
df['height'] = df['height'].astype(str) # force type str
df['height'] = df['height'].str.replace(',', '.', regex=False) # . -> ,
df['height'] = df['height'].str.replace('[A-Za-z]', '') # remove all characters
df['height'] = df['height'].str.split(';').apply(max) # pick largest value from 9;6;3
df['height'] = df['height'].apply(feet_to_m)
df['height'] = pd.to_numeric(df['height'], errors='coerce') # force float
得到
height
0 16.0000
1 7.0000
2 6.0000
3 2.4000
4 3.5000
5 NaN
6 9.0000
7 3.4544
8 1.2192
9 0.3810
希望这可以帮助