[英]How to count the number of times a value is in a column based on particular row values?
[英]How to count number of values in column based on one timestamp value python and add the count to new column
DateTime car
2015-04-16 11:57:36 bmw
2015-04-17 15:32:14 bmw
2015-04-17 19:13:43 audi
2015-04-17 05:12:16 porche
2015-04-17 13:43:31 toyota
2015-04-15 07:02:20 ferrari
在這個 dataframe df 中,我需要按時間戳 -> select 過濾一個時間戳,對於唯一的汽車列名稱,我需要計算計算唯一汽車名稱的列。
output 看起來像這樣。 讓我們說如果我們給 2015-04-16 11:57:36
car count
bmw 1
audi 1
porche 1
toyota 1
ferrari 1
我試過這樣的東西,但沒有帶時間戳的想法過濾器。 任何人都可以幫助我我陷入了這一部分。 對於 df['car'].unique() 中的汽車:num = df[df['car'] == car].apply(len)
你可以像這樣用 cumcount 做一個 groupby:
import pandas as pd
d = {'DateTime': ['2015-04-16 11:57:36', '2015-04-17 15:32:14', '2015-04-17 19:13:43','2015-04-17 05:12:16','2015-04-17 13:43:31','2015-04-15 07:02:20'], 'car': ['bmw', 'bmw','audi', 'porche','toyota','ferrari']}
df = pd.DataFrame(data=d)
df["Count"] = df.groupby("DateTime").cumcount() + 1
print(df)
Output
DateTime car Count
0 2015-04-16 11:57:36 bmw 1
1 2015-04-17 15:32:14 bmw 1
2 2015-04-17 19:13:43 audi 1
3 2015-04-17 05:12:16 porche 1
4 2015-04-17 13:43:31 toyota 1
5 2015-04-15 07:02:20 ferrari 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.