[英]Assign values to a pandas dataframe column filtered by index and column
I have a pandas DataFrame with a DateTime index and two columns called 'text'
and 'labels'
. 我有一个带有DateTime索引的熊猫DataFrame和两个名为
'text'
和'labels'
。 I want to assign the value of labels which have value =2
and lie within a DateTime index range with value =50
我想分配
labels which have value =2
且位于DateTime索引范围内且value =50
的labels which have value =2
value =50
I tried using, 我尝试使用
df[df['labels']==2]['2017-02-01 05:03:25+00:00':'2017-02-01 05:05:55+00:00']['labels']=50
I am able to view the DataFrame filtered by DataTime index (rows) and columns but not able to assign it 我能够查看按DataTime索引(行)和列过滤的DataFrame,但无法分配它
Also tried 也尝试过
df.loc[df['2017-03-13 00:00:00':'2017-03-23 00:00:00'], df['labels']==2]=50
but it threw an error 但它抛出了一个错误
df looks like df看起来像
created text labels
2017-02-01 05:03:25+00:00 break john cena eyelash grow 4
2017-02-01 05:05:55+00:00 eyelash tooooo much sweeti definit 2
2017-02-01 05:14:57+00:00 come eyelash 2
created is the DateTime index and 'text' and 'labels' are the columns of the DataFrame 创建的是DateTime索引,“文本”和“标签”是DataFrame的列
df[df['labels']==2]['2017-02-01 05:03:25+00:00':'2017-02-01 05:05:55+00:00']['labels']
filters the DataFrame but doesn't assign it if we set it equal to a value 过滤DataFrame但如果我们将其设置为等于值则不分配它
On assigning the DataFrame for created between '2017-02-01 05:03:25+00:00':'2017-02-01 05:05:55+00:00'
and labels =2
for labels=50 I expect the result to be like this 在分配要在
'2017-02-01 05:03:25+00:00':'2017-02-01 05:05:55+00:00'
05:03:25 '2017-02-01 05:03:25+00:00':'2017-02-01 05:05:55+00:00'
05:05:55 '2017-02-01 05:03:25+00:00':'2017-02-01 05:05:55+00:00'
和labels =2
的label = 50之间创建的DataFrame时,我期望结果像这样
created text labels
2017-02-01 05:03:25+00:00 break john cena eyelash grow 4
2017-02-01 05:05:55+00:00 eyelash tooooo much sweeti definit 50
2017-02-01 05:14:57+00:00 come eyelash 2
Let us do get_level_values
让我们来做
get_level_values
s=df.index.get_level_values(0)
m=(s>'2017-02-01 05:03:25+00:00') & (s<='2017-02-01 05:05:55+00:00')
df.loc[m&(df.labels==2),'lable']=50
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.