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
In this dataframe df I need to filter by timestamp -> select one timestamp and for unique car column names I need have to count column which counts unique car names.
Something output looks like this. lets say if we give 2015-04-16 11:57:36
car count
bmw 1
audi 1
porche 1
toyota 1
ferrari 1
I tried something like this but dont have an idea filter with timestamp. Can anyone help me I got stuck in this part. for car in df['car'].unique(): num = df[df['car'] == car].apply(len)
You can do a groupby with cumcount like this:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.