首页 > 解决方案 > TypeError: 尝试使用 df.diff() 时 -: 'str' 和 'str' 不支持的操作数类型

问题描述

在我的程序中运行 df.diff() 代码时出现值错误。我的目标是获得一个新列,该列显示 ClientId_Count 列中的行之间的变化。

我尝试将 int64 变量转换为浮点变量,但仍然存在问题。我想知道这是否可能是因为 TimePeriod 列是一个字符串变量?如果是这样,我如何使用 df.diff() 仅计算 ClientId_Count 列上的差异?

在此处输入图像描述

我用来获取此数据框的代码如下(我认为查询并不重要,但我将它们包括在内以防万一):

a = '''SELECT distinct [ClientId]
  FROM [GB_Msi_P1].[dbo].[table]
  where EffectiveDate >= '2018-11-01 00:00:00.000' '''

client = pd.read_sql(a, sql_conn)


b = '''select a.TimePeriodId, a.ClientId, a.BenefitCode, a.TerminationDate, a.EffectiveDate 
from [GB_Msi_P1].[dbo].[table] as a
where EffectiveDate >= '2018-11-01 00:00:00.000' and a.BenefitCode in ('25', '26', '29', '46', '66') 
order by EffectiveDate desc'''

benefit = pd.read_sql(b, sql_conn)
benefit['ClientId'].nunique()

new_clients = pd.merge(client, benefit, on = ['ClientId']).drop(columns=['TerminationDate'], axis = 1).drop_duplicates()
new_clients['TimePeriodId'] = new_clients['TimePeriodId'].astype(str)

#count clients by distinct name of client
new_clients_optional = new_clients.groupby(['TimePeriodId'])[['ClientId']].count().rename(columns={'ClientId': 'ClientId_Count'}).reset_index()


#display as discrete difference bwteen each time period Id
discrete_change_NCO = new_clients_optional.diff()

这给出了错误:

TypeError: unsupported operand type(s) for -: 'str' and 'str'

标签: pythonpandastypeerror

解决方案


是的,问题几乎可以肯定是您应用于diff不适用的列。我们无法判断您的数据类型是什么,因为您没有在代码中检查它们,也没有给我们实际的数据框。

正如您所建议的,正确设计此方法的方法是diff仅应用于您需要该数据的列。将列提取为新框架或视图;适用于此diff

temp = new_clients_optional["ClientId_Count"]
discrete_change_NCO = temp.diff()

您可能希望将这些行折叠在一起,然后放入其他代码中。


推荐阅读