Slicing dataframe caught error "TypeError: tuple indices must be integers or slices, not str"

Viewed 63

I want to slice df to form df1 based on the Data value.

df:

           Id   Timestamp               Data
106272  106273  2013-09-10 16:40:40.467 86.0
106273  106274  2013-09-10 16:40:41.267 86.0
106274  106275  2013-09-10 16:40:42.053 59.0
106275  106276  2013-09-10 16:40:42.857 52.0
106278  106279  2013-09-10 16:41:00.173 61.5

I then sliced df if Data is in range of [20, 100], with code:

df_copy = df.copy()
df1 = df_copy[(df_copy["Data"]>=20) & (df_copy["Data"]<=100)]

This worked fine.

I then wanted to group both df and df1 by date of Timestamp:

import datetime
df['Date'] = [datetime.datetime.date(d) for d in df['Timestamp']]

x = pd.DataFrame(df.groupby(['Date']).size())
x.columns = ['values']

# -----------------------------------

df1['Date'] = [datetime.datetime.date(d) for d in df1['Timestamp']]

x1 = pd.DataFrame(df1.groupby(['Date']).size())
x1.columns = ['values']

However, it worked only for df but caught error for df1:

TypeError                                 Traceback (most recent call last)
<ipython-input-15-2ddde01b3d65> in <module>

---> 12 df1['Date'] = [datetime.datetime.date(d) for d in df1['Timestamp']]
     13 
     14 x1 = pd.DataFrame(df1.groupby(['Date']).size())

TypeError: tuple indices must be integers or slices, not str

Why?

1 Answers

New column with lsit comprehension and DataFrame constructor is not necesary, use Series.dt.date with Series.to_frame:

x = (df.groupby(df['Timestamp'].dt.date)
       .size()
       .to_frame('values'))


df1 = df[(df["Data"]>=20) & (df["Data"]<=100)].copy()

x1 = (df1.groupby(df1['Timestamp'].dt.date)
         .size()
         .to_frame('values'))
Related