繁体   English   中英

将带有 % 符号的分类变量转换为数值变量 Python Pandas

[英]Converting Categorical Variable with % Sign to Numerical Variable Python Pandas

dt = {'tensile_strength': ['15%', '15%', '20%', '20%', '25%', '25%', '30%', '30%'], 
      'cotton_pct': [7, 7, 12, 17, 14, 18, 19, 25]}
mydt = pd.DataFrame(dt, columns = ['tensile_strength', 'cotton_pct'])

在我上面的数据集中,“cotton_pct”是一个分类变量。 对于“cotton_pct”,如何创建一个新变量,它是cotton_pct 的数字表示?

您可以通过.str访问整个列,之后您可以将.replace()应用于该列的所有元素。 转换为'int' ,并保存回df

mydt['tensile_strength'] = mydt['tensile_strength'].str.replace("%", '').astype('int')

您可以使用:

mydt['new_col'] = pd.to_numeric(mydt['tensile_strength'].str.strip('%'))

注意。 在这里使用一个新列,但你当然可以覆盖tensile_strength

输出:

  tensile_strength  cotton_pct  new_col
0              15%           7       15
1              15%           7       15
2              20%          12       20
3              20%          17       20
4              25%          14       25
5              25%          18       25
6              30%          19       30
7              30%          25       30

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM