Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.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_Type Conversion_Pandas Groupby - Fatal编程技术网

Python 尝试从对象转换为整数时出现无效的对象错误

Python 尝试从对象转换为整数时出现无效的对象错误,python,pandas,type-conversion,pandas-groupby,Python,Pandas,Type Conversion,Pandas Groupby,我很清楚以前也有人问过类似的问题,但在尝试了大多数传统方法后,我完全不知所措 我有一个由多个变量组成的数据框架,我从中选择了5个变量,并将这些变量分组到一个公共属性:“城市” 我试图根据每个城市从属性“driver_count”中得出唯一值: city driver_count type date fare ride_id 0 Kelseyland 63 Urban 2016-08-19 04:27:52 5.51 62460065

我很清楚以前也有人问过类似的问题,但在尝试了大多数传统方法后,我完全不知所措

我有一个由多个变量组成的数据框架,我从中选择了5个变量,并将这些变量分组到一个公共属性:“城市”

我试图根据每个城市从属性“driver_count”中得出唯一值:

        city    driver_count    type    date    fare    ride_id
0   Kelseyland  63  Urban   2016-08-19 04:27:52 5.51    6246006544795
1   Kelseyland  63  Urban   2016-04-17 06:59:50 5.54    7466473222333
2   Kelseyland  63  Urban   2016-05-04 15:06:07 30.54   2140501382736
3   Kelseyland  63  Urban   2016-01-25 20:44:56 12.08   1896987891309
4   Kelseyland  63  Urban   2016-08-09 18:19:47 17.91   8784212854829
...
应该足够简单,对吗?我只需按“City”对数据帧进行分组,然后使用pd.unique()函数导出我唯一的“driver\u count”值

pyber_df_drivers_unique=pyber_df_cities.groupby("city") # Pulls the unique value for the number of drivers in each City
U_pyber_df_drivers = pyber_df_drivers_unique["driver_count"].unique()

>>> city
Alvarezhaven    [21]
Alyssaberg      [67]
Anitamouth      [16]
Antoniomouth    [21]
Aprilchester    [49]
...
    Name: driver_count, dtype: object
这就是我的麻烦开始的地方:我正在创建一个新的数据框来对我所有转换的属性(其他变量的平均值、计数等)进行分组,以便我可以绘制我的数据。问题是,U_pyber_df_驱动程序被分类为一个对象,而不是整数或数字类型(上面输出中的括号可能也指出了这一点)

pd.至数值:

pd.to_numeric(U_pyber_df_drivers)
>>>
ERROR Invalid object type at position 0

#What's at position 0?
U_pyber_df_drivers[0]
>>>
array([21], dtype=int64)
我不理解这个错误。我尝试过其他方法,如df.astype(str)、df.convert\u objects(convert\u numeric=True)、df.infer\u objects()、甚至pd.factorize()。。。有不同类型的错误,或者只是在将变量从对象转换为数字类型时没有做任何事情(我将详细列出所有这些错误,但鉴于这一错误是所有错误的始作俑者,我宁愿理解它,以避免将来将意粉扔到墙上)。

.str[0]所示
函数从列表中提取第一项,并假设我的dataframe只有一个元素,它可以从object转换为integer(我猜它将integer指定为类型的唯一原因是它推断了数组的类型)


我认为另一个解决方案是在pd.unique()函数中传递一个dtype参数。如果没有传递任何参数,我认为会发生的事情是pd.unique()将每个数值指定为自己的列表,每个值都定义为对象类型,因此我们最终会在列表中嵌入一个列表(例如:[[0],[1],…],而不是预期的[0,1,…])。

我猜
U pyber\U df\U drivers.str[0]
那太好了,你一定是在开玩笑吧……这很有效,谢谢……但为什么呢?我可以解释,但首先,我需要知道你的列表中是否可能有多个值?如果是,那么这可能不是一个好的解决方案,因为
.str[0]
将仅从每个列表中提取第一项。否,我从主数据框中提取了“Drivers Count”变量,因此每个“City”(index)属性只有一个值。因此,我的输出为:“Alvarezhaven市21 Alyssaberg 67 Anitamouth 16 Antoniomouth 21 Aprilchester 49(..)姓名:司机人数,数据类型:int64”