python - 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'
解决方案
是的,问题几乎可以肯定是您应用于diff
不适用的列。我们无法判断您的数据类型是什么,因为您没有在代码中检查它们,也没有给我们实际的数据框。
正如您所建议的,正确设计此方法的方法是diff
仅应用于您需要该数据的列。将列提取为新框架或视图;适用于此diff
。
temp = new_clients_optional["ClientId_Count"]
discrete_change_NCO = temp.diff()
您可能希望将这些行折叠在一起,然后放入其他代码中。
推荐阅读
- python - 如何使用python按一定大小过滤和列出s3文件夹中的所有对象
- r - 用for循环输出填充矩阵
- javascript - 我如何在这里关闭我的覆盖模式框,它不起作用
- python - 正则表达式适用于 Sublime,而不适用于 Python (Jupyter)
- python - 如何使用堆栈跟踪来告诉我应该为 Python 的 try/except 使用哪个异常
- php - PHP - 使用 2 个外键将数据插入 MySQL 表
- r - 获取R包中包含的函数列表,无需下载包
- python - 如何让数据从 Python“提交”到 SQL Server?
- sqlite - 从 SQLite 中的所有行中减去平均值
- python - keras:在源内部计算权重以输入乘法