在使用pandas将对象转换为int时得到空值



我尝试使用这个方法将列列表从str对象转换为整数

df['A'] = pd.to_numeric(df['A'], errors='coerce')
df['A'] = df['A'].apply(np.int64)

注:A列的类型为对象

但是我得到了这个错误ValueError: cannot convert float NaN to integer

我猜问题是因为exp

值中有一些空间
A
1 234
6 8374

我尝试用这行代码删除空格,但它不工作。

df['A'] = df['A'].str.replace(" ","")

有人能帮忙修复这个错误吗?

如果有多个空格需要转换,试试:

df['A'] = df['A'].str.replace(r's+','', regex=True).astype(int)

改进了MDR的答案并展示了另一种方法,您可以使用一个函数将该级数转换为一系列整数。在这个函数中,您将修复当前表示中的问题并返回一个整数。如果遇到意外错误,该函数将返回0并打印错误值。代码如下:进口re

# define the function
def clean_A(a):
try:
return int(re.sub('s+', '', a))
except ValueError as e:
print(f"errorneous value encountered {a}")
return 0
# apply this function on the series
df['A'].apply(lambda x: clean_A(x))

清空空格:

df['A'] = df['A'].str.strip()

最新更新