Pandas拆分date列实现时序排序时ValueError报错如何解决
报错原因
你用"2"作为分隔符拆分的逻辑有问题,才会触发列长度不匹配的报错:
- 不同行的date值里可能没有
"2",也可能有多个"2",拆分出来的列数不是固定的2列,和你要赋值的['month','year']两列长度对不上 - 从你给出的date示例
"8 12018"来看,月份和年份之间是用空格分隔,根本不是用"2"分隔,拆分逻辑本身就不符合数据格式
解决方法
根据你的数据格式,选下面任意一种方法拆分即可:
方法1:按空白字符拆分
如果月份和年份之间确实是用空格分隔,直接按任意数量的空白字符拆分就行:
# n=1代表最多拆分1次,拆成2列,避免后续内容有空格导致拆分多列 australia_overview[['month','year']] = australia_overview['date'].str.split(r'\s+', expand=True, n=1)
方法2:正则提取(兼容性更强)
如果分隔符不固定,直接从字符串里提取对应位置的数值更稳妥:
# 提取开头的数字作为月份,提取末尾4位数字作为年份 australia_overview['month'] = australia_overview['date'].str.extract(r'^(\d+)', expand=False) australia_overview['year'] = australia_overview['date'].str.extract(r'(\d{4})$', expand=False)
后续排序
拆分完要先转成整数类型再排序,避免字符串排序出现"10" < "2"的错误:
australia_overview = australia_overview.astype({'year': int, 'month': int}) australia_overview.sort_values(by=['year', 'month'], ascending=True, inplace=True, ignore_index=True)
内容的提问来源于stack exchange,提问作者Sam Coleman
相关产品推荐
相关产品推荐

