我有一个熊猫数据框,其中包含具有非数值的列。如何将它们转换为int / float值。
eq:
Col1 Col2
Lip_GD 267
Gly_hy_68 467
Hint_2 628
Jac+Jac 339
Lip_GD 234
Jac+Jac 267
Run Code Online (Sandbox Code Playgroud)
当我将数据读入pandas数据框时,如何将列1转换为int?
Create a mapping of each unique value in Col1 to an index value:
mapping = {k: v for v, k in enumerate(df.Col1.unique())}
>>> mapping
{'Gly_hy_68': 1, 'Hint_2': 2, 'Jac+Jac': 3, 'Lip_GD': 0}
Run Code Online (Sandbox Code Playgroud)
Then create a new column mapping the values in Col1 back to their unique identifiers.
df['Col3'] = df.Col1.map(mapping)
>>> df
Col1 Col2 Col3
0 Lip_GD 267 0
1 Gly_hy_68 467 1
2 Hint_2 628 2
3 Jac+Jac 339 3
4 Lip_GD 234 0
5 Jac+Jac 267 3
Run Code Online (Sandbox Code Playgroud)