【问题标题】:TypeError: unsupported operand type(s) for -: 'str' and 'str' when trying to use df.diff()类型错误:尝试使用 df.diff() 时 -: 'str' 和 'str' 不支持的操作数类型
【发布时间】: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 中并重现您的问题。硬编码一个小数据框;提供整个错误消息,包括回溯。跟踪您有问题的数据类型和值。
  • 将编辑并发送回。谢谢!

标签: python pandas typeerror


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 2017-05-27
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-15
    • 2019-04-08
    • 2018-07-07
    相关资源
    最近更新 更多