关于pandas的ValueError: first not supported for non-numeric data错误

import numpy as np
from pandas import DataFrame, Series
import pandas as pd

s1 = pd.Series(list("86604 "))
s1
Out[7]: 
0    8
1    6
2    6
3    0
4    4
5     
dtype: object
# 对 s1 进行 method="first" 的 rank 排序
s1.rank(method="first")

以下是报错内容:

在这里插入图片描述

解决办法:

'''
解析:错误原因是,s1的类型不对。
	 通过 pd.Series(list("86604 ")) 得到的数据类型为 object,而 list 不能对 non-numeric data 进行排序
解决办法:
	1、通过 to_numeric 函数将数据类型转为 numeric type:pd.to_numeric(s1, errors='coerce')
	[to_numeric  官方文档](https://pandas.pydata.org/pandas-docs/version/0.20/generated/pandas.to_numeric.html)
	
	2、使用列表推导式创建数据:pd.Series([np.nan if e == " " else int(e) for e in list("86604 ")])
'''

在这里插入图片描述

发布了13 篇原创文章 · 获赞 6 · 访问量 526

猜你喜欢

转载自blog.csdn.net/ljr_123/article/details/104691066
今日推荐