TypeError:尝试使用df.diff()时,'str'和'str'的操作数类型不受支持

2024-09-28 22:26:16 发布

您现在位置:Python中文网/ 问答频道 /正文

在程序中运行df.diff()代码时,我遇到一个值错误。我的目标是获得一个新列,该列显示ClientId\u Count列中行之间的更改

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

enter image description here

我用来获取此数据帧的代码如下(我认为查询无关紧要,但我只是为了以防万一才包含它们):

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'


Tags: 代码clientdfnewsqlcount错误diff
1条回答
网友
1楼 · 发布于 2024-09-28 22:26:16

是的,问题几乎肯定是您将diff应用于不适用的列。我们无法告诉您的数据类型是什么,因为您没有在代码中检查它们,并且没有给我们实际的数据帧

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

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

您可能希望将这些行折叠在一起,然后再转换成其他代码

相关问题 更多 >