【发布时间】:2020-11-28 01:23:29
【问题描述】:
在我的程序中运行 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'
【问题讨论】:
-
我们无法回答您的几个次要问题,因为您未能提供完整的minimal, reproducible example。我们应该能够将您发布的代码粘贴到我们自己的 Python IDE 中并重现您的问题。硬编码一个小数据框;提供整个错误消息,包括回溯。跟踪您有问题的数据类型和值。
-
将编辑并发送回。谢谢!