首页 > 解决方案 > 我想如何将 int 转换为 str

问题描述

我想将重要列的值组合成一个字符串,但其中一列是整数。而且真的不知道在哪里放置 str() 代码以将 int 转换为字符串。所以这是我的代码:

#create function to combine the values of the important columns into a single string
def get_important_features(data):
  important_features = []
  for i in range(0, data.shape[0]):
    important_features.append(data['Location'][i]+' '+str(data['Price'])[i]+' '+data['Property Type'][i]+' '+data['Furnishing'][i])

  return important_features


**#create a column to hold the combined strings**
df['important_features'] = get_important_features(df)

#show the data

df.head(3)

这是错误输出:

TypeError                                 Traceback (most recent call last)
<ipython-input-16-ef130dbef96b> in <module>()
      1 #create a column to hold the combined strings
----> 2 df['important_features'] = get_important_features(df)
      3 
      4 #show the data
      5 


<ipython-input-15-fda6e7b86a60> in get_important_features(data)
      3   important_features = []
      4   for i in range(0, data.shape[0]):
----> 5     important_features.append(data['Location'][i]+' '+str(data['Price'])[i]+' '+data['Property Type'][i]+' '+data['Furnishing'][i])
      6 
      7   return important_features

TypeError: must be str, not float

标签: python-3.xpandas

解决方案


谢谢你们。我已经解决了答案。谢谢大家的想法

我编辑这一行:

important_features.append(data['Location'][i]+' '+str(data['Price'][i])+' '+data['Property Type'][i]+' '+data['Furnishing'][i])

并像这样改变:

important_features.append(str(data['Location'][i])+' '+str(data['Price'][i])+' '+str(data['Property Type'][i])+' '+str(data['Furnishing'][i]) )

推荐阅读