在数据框中,所有值的类型均为 object
例如:>20
, <1
, >5
ETC。
上限 = 35
和下限 = 0
因此,如果列中的值为 <1
然后我想通过取平均值来替换该值,即 (0(下限值)+ 1)/2 = 0.5
类似地,如果值为 >20
然后我想用 (20+35(上限值))/2=27.5 替换该值
如何将现有数据框转换为所需的形式。注意: col1
中的值是字符串而不是数值。
现有数据框:
d = {'col1': ['>20', '<5', '<1','>10']}
df = pd.DataFrame(data=d)
df
col1
0 >20
1 <5
2 <1
3 >10
4 100-200
5 10-20
我要转换上面df
至:
col1
0 27.5 <--- (20+35)/2
1 2.5 <--- (5+0)/2
2 0.5 <--- (1+0)/2
3 22.5 <--- (10+35)/2
4 150 <--- (100+200)/2
5 15 <--- (10+20)/2
最佳答案
使用replace
通过子字符串,然后 pandas.eval
:
df['col2'] = pd.eval(df['col1'].replace(['>','<'], ['35+','0+'], regex=True)) / 2
print (df)
col1 col2
0 >20 27.5
1 <5 2.5
2 <1 0.5
3 >10 22.5
编辑:
df['col2'] = pd.eval(df['col1'].replace(['>','<','-'], ['35+','0+','+'], regex=True)) / 2
print (df)
col1 col2
0 >20 27.5
1 <5 2.5
2 <1 0.5
3 >10 22.5
4 100-200 150
5 10-20 15
编辑:
上面的问题解决方案仅适用于 100 行(请参阅 bug ),因此需要替代解决方案:
df = pd.read_csv('train_jqd04QH(1).csv', usecols=['experience', 'company_size'])
s1 = df['experience'].replace(['>','<', '-'], ['35+','0+', '+'], regex=True)
#added anothr repalce string, `\+$` is match last + like 1000+
s2 = df['company_size'].replace(['>','<', '-', '/', '\+$'],
['35+','0+', '+', '+', '+35'], regex=True)
df['experience'] = s1.str.split('+', expand=True).astype(float).mean(axis=1)
df['company_size'] = s2.str.split('+', expand=True).astype(float).mean(axis=1)
print (df.head())
experience company_size
0 3.0 300.0
1 14.0 5.0
2 6.0 74.5
3 14.0 74.5
4 8.0 NaN
关于python - 如何用数值替换分类值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51395527/