Python 如何使用dtype=object进行数字排序但读取\u csv?

Python 如何使用dtype=object进行数字排序但读取\u csv?,python,pandas,Python,Pandas,鉴于此简化的test.csv文件: wrong 8 7 6 3 1 2 4 5 9 10 该代码: #!/usr/bin/python import pandas as pd data = pd.read_csv('test.csv', dtype=object) counts=data['wrong'].value_counts(dropna=False) counts_converted=counts.convert_objects(convert_numeric=True) prin

鉴于此简化的test.csv文件:

wrong
8
7
6
3
1
2
4
5
9
10
该代码:

#!/usr/bin/python
import pandas as pd

data = pd.read_csv('test.csv', dtype=object)
counts=data['wrong'].value_counts(dropna=False)
counts_converted=counts.convert_objects(convert_numeric=True)

print counts_converted.sort_index()
生成以下输出:

1     1
10    1
2     1
3     1
4     1
5     1
6     1
7     1
8     1
9     1
dtype: int64
为什么最后一个print语句没有对索引1-10进行排序

在读取csv文件时,我必须强制dtype为object,以克服在列中检测混合字符、日期和数字格式的一些问题,因此删除该语句对我不起作用

我以为我可以把序列转换成数字,但它似乎不起作用

编辑问题,因为评论不允许我在不发布评论的情况下使用Enter键。。。[啊,发现了很多关于此功能的长篇大论。Shift-Enter有效。]

@EdChum建议的解决方案适用于简化案例,但不适用于生产数据。考虑一个稍微不太简单的数据文件:

wrong,right
8,a
7,b
6,c
3,d
1,
2,f
4,g
5,h
9,i
10,j
,k
11,l
倒数第二行的空值导致错误“无法将浮点NaN转换为整数”

我有很多NAN(都是空的)需要保留并在值_counts中计数

其他空单元格在转换为int64时似乎显示为非常大的负数(即-5226413792388707240)


对于我的迟钝,请提前道歉!感谢您的帮助。

在阅读后添加一个
astype
,可以正确排序

你提到你必须整理一些混合字符、日期和其他东西,在
astype
之前这样做,一切都应该很好

import pandas as pd

data = pd.read_csv('/home/mikael/test.csv', dtype=object)

# Sanitize your data here

data['wrong'] = data['wrong'].astype(int)
counts=data['wrong'].value_counts(dropna=False)
counts_converted=counts.convert_objects(convert_numeric=True)

print counts_converted.sort_index()

1     1
2     1
3     1
4     1
5     1
6     1
7     1
8     1
9     1
10    1
dtype: int64

这里的问题是,在任何类型转换之前,您在df上调用了
value\u counts
,因此您的
value\u counts
索引仍然是
object
dtype,它是
str

In [59]:

t="""wrong
8
7
6
3
1
2
4
5
9
10"""
df = pd.read_csv(io.StringIO(t), dtype=object)
counts=df['wrong'].value_counts(dropna=False)
counts.index
Out[59]:
Index(['4', '6', '2', '9', '3', '10', '5', '1', '8', '7'], dtype='object')
调用
convert\u对象
转换数据而不是索引

如果将索引类型强制转换为
np.int64
,则其排序正确:

counts.index = counts.index.astype(np.int64)
counts.sort_index()
Out[74]:
1     1
2     1
3     1
4     1
5     1
6     1
7     1
8     1
9     1
10    1
dtype: int64

您已将中的值读取为
object
这使值
str
生效,您调用
value\u counts
,然后将索引设置为您的值,然后调用
convert\u objects
但这没有效果,因为需要转换的是您的索引