首页 > 解决方案 > 如何在不获取 NaN 值的情况下将字符串列转换为数值

问题描述

在此处输入图像描述

我有字符串列,我必须将其转换为值。我使用了这段代码,不幸的是这个fillna方法在这个例子中不起作用。

我该如何解决这个问题?

这是头()

头()

data['country_txt'] = data['country_txt'].astype('float64') 
data['city'] = data['city'].astype('float64') 

我期望一个正常的结果,但实际输出都充满了 NaN 值:

country_txt 0 非空 float64 城市 0 非空 float64

标签: pythonpandas

解决方案


显然,您需要将字符串映射到integer表示形式。

有很多不同的方法可以做到这一点。

1pd.factorize

df['country_as_int'] = pd.factorize(df['country_txt'])[0]

2LabelEncoder

from sklearn.preprocessing import LabelEncoder
f = LabelEncoder()
df['country_as_int'] = f.fit_transform(df['country_txt'])

3np.unique

df['country_as_int'] = np.unique(df['country_txt'], return_inverse=True)[-1]

推荐阅读