简体   繁体   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'])

In my above dataset, 'cotton_pct' is a categorical variable.在我上面的数据集中,“cotton_pct”是一个分类变量。 For 'cotton_pct', how do I create a new variable that is a numerical representation of cotton_pct?对于“cotton_pct”,如何创建一个新变量,它是cotton_pct 的数字表示?

You can access an entire column by .str , after which you can apply .replace() to all elements of that column.您可以通过.str访问整个列,之后您可以将.replace()应用于该列的所有元素。 Convert to 'int' , and save back into the df转换为'int' ,并保存回df

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

You can use:您可以使用:

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

NB.注意。 using a new column here, but you can of course overwrite tensile_strength在这里使用一个新列,但你当然可以覆盖tensile_strength

output:输出:

  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