python - 如何通过时间累积每个 ID 的唯一行值的数量

标签 python pandas

我有一个包含日期、car_id 和目的地的数据集。

对于每一行,我想要每个 car_id 的唯一目的地的累计数量。重要的是计数器在最早的日期开始。

所需的输出是“unique_destinations”列:

          date  car_id   destination  unique_destinations
0   01/01/2019       1        Boston                    1
1   01/01/2019       2         Miami                    1
2   02/01/2019       1        Boston                    1
3   02/01/2019       2       Orlando                    2
4   03/01/2019       1      New York                    2
5   03/01/2019       2         Tampa                    3
6   04/01/2019       1        Boston                    2
7   04/01/2019       2         Miami                    3
8   05/01/2019       1    Washington                    3
9   05/01/2019       2  Jacksonville                    4
10  06/01/2019       1      New York                    3
11  06/02/2019       2       Atlanta                    5

最佳答案

好吧,这可能效率不高,但它是一种方法:)

def check(data):
    seen = []
    flag = 0
    for index,row in data.iterrows():
        if row['destination'] not in seen:
            flag+=1
            data['unique_destinations'][index] = flag
            seen.append(row['destination'])
        else:
            data['unique_destinations'][index] = flag
    return data

df['unique_destinations'] = 0
df.groupby('car_id').apply(check)

输出

0     1
1     1
2     1
3     2
4     2
5     3
6     2
7     3
8     3
9     4
10    3
11    5
Name: unique_destinations, dtype: int64

关于python - 如何通过时间累积每个 ID 的唯一行值的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55495086/

相关文章:

python - 合并两个 pandas 数据框并跳过右侧的公共(public)列

python - 将一列按另一列的值分组

python - Pandas 日期时间问题

python - 使用python从文本文件插入mysql表

Pythonic,自定义警告

python pandas np.where 来自另一列的值

python - 在 Pandas Dataframe Cell 中查找特定格式

python - 使用 Whoosh 的深度 NLP 管道

python - 这个 .write 命令有什么问题?

python - 如何将 mapinfo 文件加载到 geopandas 中