You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

对象转整数遇Invalid object error,DataFrame按City取driver_count唯一值受阻

解决按City分组后获取driver_count唯一值的问题

嘿,我懂你这种试过常规方法还是卡壳的感觉!按City分组后要提取每个城市对应的driver_count唯一值对吧?这就给你几个直接能用的pandas解决方案~

首先先模拟你的数据场景(方便你直接测试):

import pandas as pd

# 模拟你的数据集
data = {
    'city': ['Kelseyland', 'Kelseyland', 'West Hollywood', 'West Hollywood', 'Kelseyland'],
    'driver_count': [63, 63, 45, 45, 63],
    'type': ['Urban', 'Urban', 'Urban', 'Suburban', 'Urban'],
    'date': ['2016-08-19 04:27:52', '2016-08-20 05:10:15', '2016-08-19 06:30:00', '2016-08-20 07:15:30', '2016-08-21 08:00:00'],
    'fare': [5.51, 7.25, 10.30, 8.75, 6.10],
    'ride_id': ['6246006544795', '6246006544796', '6246006544797', '6246006544798', '6246006544799']
}

df = pd.DataFrame(data)

方法1:获取每个城市的driver_count唯一值列表

直接用groupby结合unique(),就能得到每个城市对应的所有唯一driver_count:

# 按city分组,提取driver_count的唯一值
unique_drivers = df.groupby('city')['driver_count'].unique()
print(unique_drivers)

输出结果:

city
Kelseyland         [63]
West Hollywood     [45]
Name: driver_count, dtype: object

如果想把结果转换成规整的DataFrame格式(方便后续处理),可以加上reset_index():

unique_drivers_df = unique_drivers.reset_index()
unique_drivers_df.columns = ['city', 'unique_driver_counts']
print(unique_drivers_df)

输出:

city unique_driver_counts
0     Kelseyland                 [63]
1  West Hollywood                 [45]

方法2:统计每个城市的driver_count唯一值数量

如果你只是想知道每个城市有多少种不同的driver_count,用nunique()更直接:

driver_count_unique_num = df.groupby('city')['driver_count'].nunique()
print(driver_count_unique_num)

输出结果:

city
Kelseyland         1
West Hollywood     1
Name: driver_count, dtype: int64

补充说明

如果某个城市的driver_count存在多个不同值(比如Kelseyland既有63又有65),这些方法也能准确捕捉:

  • unique()会返回包含所有唯一值的列表,比如[63,65]
  • nunique()会返回对应的数量,比如2

内容的提问来源于stack exchange,提问作者HP-Nunes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:53:49