【发布时间】:2020-10-08 14:48:50
【问题描述】:
我有一个数据集,其中一列包含一些行的整数和其他行的字符串。 列类型为对象。
例如:
Index Column of interest
1 21678849
2 37464859
3 barbara
4 28394821
5 francis
我无法使用 .astype('str') 强制列更改类型。而且我无法使用 .isstring、.isdigit 或 .isinstance。 我试过查看solutions for converting on objects to string,但这些似乎不起作用。
我也试过了:
[True if x.isin([1,2,3,4,5,6,7,8,9,0]) else False for x in df['column_of_interest']]
但这只是给了我:AttributeError: 'str' object has no attribute 'isin'
有人对我如何管理这个有任何其他想法吗?
理想情况下,我想创建第三列,用于对行是 int 还是 str 进行分类。
【问题讨论】:
-
您可以使用
pd.to_numeric(df['Column of interest'],errors='coerce')将您的字符串强制为空。 -
所以这也可以。然后我只需要添加另一个步骤来制作识别某事物是 int 还是 Null 的列。
-
你可以将它链接成一个,
df['DataType'] = np.where(pd.to_numeric(df['Column of interest'],errors='coerce').isnull(), 'Text','Number')有很多方法可以做到这一点,pandas 内置了你也可以随时利用的数据类型。