Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫-如何分割值_计数?_Python_Pandas - Fatal编程技术网

Python 熊猫-如何分割值_计数?

Python 熊猫-如何分割值_计数?,python,pandas,Python,Pandas,我想切片一个值\u counts(): 但我有一个错误: > sur_perimetre[col].value_counts()[:5] KeyError: 5.0 与ix相同: > sur_perimetre[col].value_counts().ix[:5] KeyError: 5.0 你会怎么处理 编辑 也许: pd.DataFrame(sur_perimetre[col].value_counts()).reset_index()[:5] 方法1: 您需要注意,值_c

我想切片一个值\u counts():

但我有一个错误:

> sur_perimetre[col].value_counts()[:5]
KeyError: 5.0
与ix相同:

> sur_perimetre[col].value_counts().ix[:5]
KeyError: 5.0
你会怎么处理

编辑 也许:

pd.DataFrame(sur_perimetre[col].value_counts()).reset_index()[:5]

方法1:

您需要注意,值_counts()返回一个系列对象。您可以像处理任何其他系列一样处理它并获取值。您甚至可以用它构建一个新的数据帧

In [1]: import pandas as pd

In [2]: df = pd.DataFrame([1,2,3,3,4,5], columns=['C1'])

In [3]: vc = df.C1.value_counts()

In [4]: type(vc)
Out[4]: pandas.core.series.Series

In [5]: vc.values
Out[5]: array([2, 1, 1, 1, 1])

In [6]: vc.values[:2]
Out[6]: array([2, 1])

In [7]: vc.index.values
Out[7]: array([3, 5, 4, 2, 1])

In [8]: df2 = pd.DataFrame({'value':vc.index, 'count':vc.values})

In [8]: df2
Out[8]: 
   count  value
0      2      3
1      1      5
2      1      4
3      1      2
4      1      1
方法2:

然后,我试图重新生成您提到的错误。但是,使用DF中的一个列,我没有得到与您提到的相同的表示法中的任何错误

In [1]: import pandas as pd

In [2]: df = pd.DataFrame([1,2,3,3,4,5], columns=['C1'])

In [3]: df['C1'].value_counts()[:3]
Out[3]: 
3    2
5    1
4    1
Name: C1, dtype: int64      

In [4]: df.C1.value_counts()[:5]
Out[4]: 
3    2
5    1
4    1
2    1
1    1
Name: C1, dtype: int64

In [5]: pd.__version__
Out[5]: u'0.17.1'

希望有帮助

使用
iloc
,即
sur\u perimeter[col].value\u counts().iloc[:5]
我刚刚试过,这两种方法都很好。
ix
iloc
都很有效。
sur\u perimeter[col].value\u counts()[:5]
给出了0.18.0中的前5个值。但最好是直言不讳。我也会选择
.iloc
。@romain,你的版本是什么?我使用的是0.17.1,直接切片也适用于我。啊,好吧,这是因为这些值是浮动的。当它们是整数时,工作正常。也许是个bug?我相信[iloc]就是我想要的功能
In [1]: import pandas as pd

In [2]: df = pd.DataFrame([1,2,3,3,4,5], columns=['C1'])

In [3]: df['C1'].value_counts()[:3]
Out[3]: 
3    2
5    1
4    1
Name: C1, dtype: int64      

In [4]: df.C1.value_counts()[:5]
Out[4]: 
3    2
5    1
4    1
2    1
1    1
Name: C1, dtype: int64

In [5]: pd.__version__
Out[5]: u'0.17.1'