根据索引的日期时间过滤器设置列值 [英] Set column value based on indexed datetime filter
问题描述
我想基于python,pandas中的白天过滤器(DateTime值在索引列中)填充列的值.
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.
所以我尝试了:
df[df['2017.01.19 12:30:00':'2017.01.19 15:10:00'], "column_value"] = "something"
但是我收到TypeError: 'DataFrame' objects are mutable, thus they cannot be hashed
类型错误.
如果我尝试:df[df['2017.01.19 12:30:00':'2017.01.19 15:10:00']]
,
我收到Must pass DataFrame with boolean values only
错误.
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.
因此,请帮助我,让我知道如何基于索引的DateTime过滤器设置列的值.
So please help me and let me know how to set the value of a column based on an indexed DateTime filter.
谢谢.
推荐答案
使用 DataFrame.loc
,日期时间与-
代替,.
:
df.loc['2017-01-19 12:30:00':'2017-01-19 15:10:00', "column_value"] = "something"
示例:
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
这篇关于根据索引的日期时间过滤器设置列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!