Python 将dataframe列中的整数值更改为字符串

Python 将dataframe列中的整数值更改为字符串,python,string,dataframe,Python,String,Dataframe,我有一个dataframe,我想更改一个列,该列当前具有表示价格差异的整数值。我想更改它们,以便大于0的值表示“更大”,小于0的值表示“更小” 我试过:month['Difference']=np.wheremonth.Difference>0.0,'biger',month.Difference 但出现错误:“>”在“str”和“float”实例之间不受支持 如何解决此问题?这对您有用吗 month['Difference'] = np.where((month['Difference'].a

我有一个dataframe,我想更改一个列,该列当前具有表示价格差异的整数值。我想更改它们,以便大于0的值表示“更大”,小于0的值表示“更小”

我试过:month['Difference']=np.wheremonth.Difference>0.0,'biger',month.Difference

但出现错误:“>”在“str”和“float”实例之间不受支持


如何解决此问题?

这对您有用吗

month['Difference'] = np.where((month['Difference'].astype(float) > 0),'Bigger',month.Difference)
也许最好不要覆盖现有列,因此创建一个新列

month['new_difference'] = np.where((month['Difference'].astype(float) > 0),'Bigger',month.Difference)
如果你没有零值

month = pd.DataFrame({'Difference':[1,2,3,4,-1,-1]})

month['new_difference'] = np.where((month['Difference'].astype(float) > 0),'Increase','Decrease')

问题是列值当前被视为字符串

我相信使用.apply最适合您的用例:

def difference_to_string(diff):
    if float(diff) > 0.0:
       return "Bigger"
    else:
       return "Smaller"

month['Difference'] = month['Difference'].apply(difference_to_string)
或者,您可以通过以下方式将整个列转换为float类型:

month['Difference'] = month['Difference'].astype(float)

你的方法应该行得通。

谢谢!这已经消除了错误。虽然我尝试将相同的值应用于“较小”的值,但之前写为“增加”的值已返回到其初始数值,剩下的是“较小”。你知道如何应用这两个条件吗?谢谢你的时间:嘿,willyg改变了答案这对你有帮助吗?如果有,请投票;非常感谢你,你的最后一行对我有用!我很感激:很高兴听到。你能把你的问题设为已回答吗;?我该怎么做?非常感谢:我的荣幸