将包含字符串的列与包含浮点数的列合并

Merge a column containing strings with a column containing floats

我有一个 (geo)dataframe,其中包含一个包含位置名称的列和一个包含浮点数的列,我想合并它们。

geopandas 中城市数据集的示例(带有额外的列):

 Name          geometry    GDP
Vatican City  POINT(...)  20353.42

我想合并它们所以我有:梵蒂冈城:20353.42 我尝试了什么:

cities['name-gdp'] = cities['name'].astype(str).str.cat(cities['GDP'], sep =': ')

但是我收到以下错误: TypeError:序列项 1:预期的 str 实例,float found

似乎需要将 float GDP 列转换为 strings:

cities['name-gdp'] = cities['name'].str.cat(cities['GDP'].astype(str), sep =': ')

但是如果一些 NaNs 并且需要输出为 NaNs:

cities = pd.DataFrame({'name':['q','w','e'], 'GDP':[10.5,20.3, np.nan]})
print (cities)
    GDP name
0  10.5    q
1  20.3    w
2   NaN    e

gdp = cities['GDP'].mask(cities['GDP'].notnull(),cities['GDP'].astype(str))
print (gdp)
0    10.5
1    20.3
2     NaN
Name: GDP, dtype: object

print (gdp.apply(type))
0      <class 'str'>
1      <class 'str'>
2    <class 'float'>
Name: GDP, dtype: object

cities['name-gdp'] = cities['name'].astype(str).str.cat(gdp, sep =': ')
print (cities)
    GDP name name-gdp
0  10.5    q  q: 10.5
1  20.3    w  w: 20.3
2   NaN    e      NaN

第一个解决方案也可以使用,但随后使用字符串 nan 并得到:

cities['name-gdp'] = cities['name'].str.cat(cities['GDP'].astype(str), sep =': ')
print (cities)
     GDP name name-gdp
0  10.5    q  q: 10.5
1  20.3    w  w: 20.3
2   NaN    e   e: nan