1

I would like to fill the values of a column based on a daytime filter (the DateTime values are in the index column) in python, pandas.

The problem I am facing is that my datetimes are already set as index, therefore, the "old way" I was solving this problem does not work.

So far for similar problems I was using this approach:

df.loc[df['filter'] > 0, 'column_value'] = 1

However now the 'filter' column is actually the index and I filter it between two dates, so there is no boolean in the first place.

So I tried:

df[df['2017.01.19  12:30:00':'2017.01.19  15:10:00'], "column_value"] = "something"

But I get the TypeError: 'DataFrame' objects are mutable, thus they cannot be hashed type error.

If I try: df[df['2017.01.19 12:30:00':'2017.01.19 15:10:00']], I get the Must pass DataFrame with boolean values only error.

So please help me and let me know how to set the value of a column based on an indexed DateTime filter.

Thank you in advance.

bugfreerammohan
  • 1,471
  • 1
  • 7
  • 22
hunsnowboarder
  • 170
  • 2
  • 18

1 Answers1

1

Use DataFrame.loc with datetimes with - instead .:

df.loc['2017-01-19 12:30:00':'2017-01-19 15:10:00', "column_value"] = "something"

Sample:

idx =  pd.date_range('2017-01-19 12:00:00', '2017-01-19 16:30:00', freq='10T')
df = pd.DataFrame({'column_value': ['a'] * len(idx)}, index = idx)

df.loc['2017-01-19 12:30:00':'2017-01-19 15:10:00', "column_value"] = "something"
print (df)
                    column_value
2017-01-19 12:00:00            a
2017-01-19 12:10:00            a
2017-01-19 12:20:00            a
2017-01-19 12:30:00    something
2017-01-19 12:40:00    something
2017-01-19 12:50:00    something
2017-01-19 13:00:00    something
2017-01-19 13:10:00    something
2017-01-19 13:20:00    something
2017-01-19 13:30:00    something
2017-01-19 13:40:00    something
2017-01-19 13:50:00    something
2017-01-19 14:00:00    something
2017-01-19 14:10:00    something
2017-01-19 14:20:00    something
2017-01-19 14:30:00    something
2017-01-19 14:40:00    something
2017-01-19 14:50:00    something
2017-01-19 15:00:00    something
2017-01-19 15:10:00    something
2017-01-19 15:20:00            a
2017-01-19 15:30:00            a
2017-01-19 15:40:00            a
2017-01-19 15:50:00            a
2017-01-19 16:00:00            a
2017-01-19 16:10:00            a
2017-01-19 16:20:00            a
2017-01-19 16:30:00            a
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252