I have the following dataframe snippet:
Full dataframe: ip time cik crawler
ts
2019-03-11 00:00:01 71.155.177.ide 00:00:01 1262327 0.0
2019-03-11 00:00:02 71.155.177.ide 00:00:02 1262329 0.0
2019-03-11 00:00:05 69.243.218.cah 00:00:05 751200 0.0
2019-03-11 00:00:08 172.173.121.efb 00:00:08 881890 0.0
2019-03-11 00:00:09 216.254.60.idd 00:00:09 1219169 0.0
2019-03-11 00:00:09 64.18.197.gjc 00:00:09 1261705 0.0
2019-03-11 00:00:09 64.18.197.gjc 00:00:09 1261734 0.0
2019-03-11 00:00:10 64.18.197.gjc 00:00:10 1263094 0.0
2019-03-11 00:00:10 64.18.197.gjc 00:00:10 1264242 0.0
2019-03-11 00:00:10 64.18.197.gjc 00:00:10 1264242 0.0
I want to group by IPs and then use some function to count:
1) How many unique CIKs are per IP in 1 minute
2) How many CIKs (in total) are per IP in 1 minute.
I have tried the resample function, but I don't know how to make it count in the way I want it. My code is the following:
dataframe = pd.read_csv(path + "log20060702.csv", usecols=['cik', 'ip', 'time', 'crawler'])
dataframe = dataframe[dataframe['crawler'] == 0]
dataframe['cik'] = pd.to_numeric(dataframe['cik'], downcast='integer')
dataframe['ts'] = pd.to_datetime((dataframe['time']))
dataframe = dataframe.set_index(['ts'])
print("Full dataframe: ", dataframe.head(10))
df_dict = dataframe.groupby("ip")
counter = 0
for key, df_values in df_dict:
counter += 1
print("df values: ", df_values)
# df_values = df_values.resample("5T").count()
if counter == 5:
break
Or if someone could tell me how can I group by IP and every 1 minute and the rest I can do myself. I'm not looking necessarily for the full solution, some guidance would be much appreciated.
Use groupby with DataFrameGroupBy.resample and aggregate SeriesGroupBy.nunique with count by DataFrameGroupBy.size :
df = dataframe.groupby("ip").resample('1Min')['cik'].agg(['nunique','size'])
print (df)
nunique size
ip ts
172.173.121.efb 2019-03-11 1 1
216.254.60.idd 2019-03-11 1 1
64.18.197.gjc 2019-03-11 4 5
69.243.218.cah 2019-03-11 1 1
71.155.177.ide 2019-03-11 2 2
Or use Grouper:
df = dataframe.groupby(["ip", pd.Grouper(freq='1Min')])['cik'].agg(['nunique','size'])
print (df)
nunique size
ip ts
172.173.121.efb 2019-03-11 1 1
216.254.60.idd 2019-03-11 1 1
64.18.197.gjc 2019-03-11 4 5
69.243.218.cah 2019-03-11 1 1
71.155.177.ide 2019-03-11 2 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With