pandas 混合型到整数 [英] Pandas Mixed Type to Integer
本文介绍了 pandas 混合型到整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出以下数据框:
import pandas as pd
df = pd.DataFrame(
{'A':['A','B','C','D'],
'C':['1','12','*','8']
})
df
A C
0 A 1
1 B 12
2 C *
3 D 8
我想删除所有'*'实例,并将其余实例转换为整数. 我的实际数据中可能存在"nan"或"NaN"的某些情况.
I'd like to remove all instances of '*' and convert the rest to integer. There may be some instances of 'nan' or 'NaN' in my actual data.
推荐答案
您可以使用pd.to_numeric
将C
列转换为数字值.传递errors='coerce
'告诉pd.to_numeric
将非数字值设置为NaN
.
You could use pd.to_numeric
to convert the C
column to numeric values. Passing errors='coerce
' tells pd.to_numeric
to set non-numeric values to NaN
.
import pandas as pd
df = pd.DataFrame(
{'A':['A','B','C','D'],
'C':['1','12','*','8'] })
df['C'] = pd.to_numeric(df['C'], errors='coerce')
print(df)
打印
A C
0 A 1.0
1 B 12.0
2 C NaN
3 D 8.0
由于仅在具有浮点dtype(或object
dtype)的列中允许使用NaN值,因此无法将该列设置为整数dtype.
Since NaN values are only allowed in columns with floating-point dtype (or object
dtype), the column can not be set to an integer dtype.
这篇关于 pandas 混合型到整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文