我有拥抱数据,其中在一个列中,像emp_code是有些开始的2,有些是饥饿的l(l(。当我阅读时,CSV将以字符串格式显示所有值。我希望整数应该在整数中。
-
df.apply(pd.to_numeric, errors='ignore')
-首次尝试 -
df["new"] = df['Agency FOS'].str.split(expand=True,)
-第二次尝试
ABC = []
for row in df["New"] :
if row == "I": ABC.append (row.value)
else : ABC.append ((row.value) * 1)
df["ABC"] = ABC
234567 = 23567(数据类型应该是整数(
i2345 = i2345(数据类型应为字符串(
通常在pandas中,列中的所有值都具有相同的类型。因此,您的列可以是int
类型,也可以是object
类型。您可以通过两种方式帮助自己:
-
您使用对象存储列并在列中转换单个值,即整数为整数。
-
您可以将数据划分为两列,一列用于
int
,一个用于str
。
我更喜欢第二个,但这取决于您打算使用数据做什么。我更喜欢它,因为如果很难在列上计算一些int
的值,您会从中获得什么?
这是两个变体的工作方式。首先,我定义了一个测试数据框和一个索引器,该索引可以标识所有int
值,或者更高的所有值,这些值并非以ELL开头。然后将索引器用于两个变体:
df= pd.DataFrame(dict(mixed_col=['l123', '23422', '8343', 'l2232']))
indexer= ~df['mixed_col'].str.startswith('l')
# a maybe safer variant for an indexer would be
indexer= ~df['mixed_col'].str.isnumeric()
# variant 1
df.loc[indexer, 'mixed_col']= df.loc[indexer, 'mixed_col'].map(int)
# variant 2: first create an empty new column with nullable INTSs, then
# set the values in it, which represent INTs in mixed_col
df['int_col']= pd.Series([None]*df.shape[0], index=df.index, dtype='Int64')
# note the lower case int64 instead of Int64
# for Int64 I got an conversion error
# Int64 is relatively new in Pandas, so you maybe need
# need to update your pandas version.
# Please see below (***), in case you need to do this with an
# older version of pandas, that doen't support Int64
df.loc[indexer, 'int_col']= df.loc[indexer, 'mixed_col'].astype('int64')
原始列中的数据类型具有类型:
>>> df['mixed_col'].map(type)
0 <class 'str'>
1 <class 'str'>
2 <class 'str'>
3 <class 'str'>
Name: mixed_col, dtype: object
第一个变体的结果看起来像:
>>> df['mixed_col'].map(type)
0 <class 'str'>
1 <class 'int'>
2 <class 'int'>
3 <class 'str'>
Name: mixed_col, dtype: object
第二个变体的结果看起来像:
>>> df
mixed_col int_col
0 l123 NaN
1 23422 23422
2 8343 8343
3 l2232 NaN
>>> df.dtypes
mixed_col object
int_col Int64
dtype: object
顺便说一句。如果您需要与read_csv
结合使用,并且决定使用变体1,则可以在上面描述的后处理步骤中执行此操作,或者您可以创建自己的转换功能并将其作为转换器传递给read_csv
。看起来像
df= pd.read_csv(filename, ..., converters={'mixed_col': lambda v: int(v) if v.isnumeric() else v})
***
如果您需要用旧版本的熊猫来实现一种变体2,它会变得更加复杂。您必须使用列列值以 l
(ell(开头的所有行使用默认值,并且可能必须引入一个指示列,该列告诉您哪个值实际上是从字符串转换为从字符串转换而来的。例如。通过将索引器存储在单独的列中,并将其称为" is_numeric"之类的东西。也许已经说服您更新大熊猫,如果您还没有这样做: - (