pandas 数据框无法将值分配给切片子集 [英] pandas dataframe fails to assign value to slice subset
本文介绍了 pandas 数据框无法将值分配给切片子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试更改切片中除第一个值之外的所有值,但是它不起作用...我在做什么错了?
I'm trying to change all values in the slice except the first one but it does not work... what am i doing wrong ?
print(test)
test.loc[(test.col_1==-5)&(test.index>'2018-07-17 13:00:00')&(test.index<'2018-07-17 14:00:00'),['col_1']][1:]=-1
print(test)
提供以下输出
17/07/2018 13:51:00 -5
17/07/2018 13:52:00 -1
17/07/2018 13:53:00 -5
17/07/2018 13:54:00 -5
17/07/2018 13:55:00 -5
17/07/2018 13:56:00 -5
17/07/2018 13:57:00 -5
17/07/2018 13:58:00 -5
17/07/2018 13:59:00 -5
17/07/2018 13:51:00 -5
17/07/2018 13:52:00 -1
17/07/2018 13:53:00 -5
17/07/2018 13:54:00 -5
17/07/2018 13:55:00 -5
17/07/2018 13:56:00 -5
17/07/2018 13:57:00 -5
17/07/2018 13:58:00 -5
17/07/2018 13:59:00 -5
而我期望第二个输出是
17/07/2018 13:51:00 -5
17/07/2018 13:52:00 -1
17/07/2018 13:53:00 -1
17/07/2018 13:54:00 -1
17/07/2018 13:55:00 -1
17/07/2018 13:56:00 -1
17/07/2018 13:57:00 -1
17/07/2018 13:58:00 -1
17/07/2018 13:59:00 -1
推荐答案
您可以使用 numpy.where
并使用索引 [1:]
来排除第一次条件是 True
.这是一个最小的示例:
You can use numpy.where
and use indexing [1:]
to exclude the first time the criterion is True
. Here's a minimal example:
df = pd.DataFrame([[1, -5], [2, -5], [3, -1], [4, -5], [5, -5], [6, -1]],
columns=['col1', 'col2'])
df.iloc[np.where(df['col1'].between(2, 5))[0][1:], 1] = -1
print(df)
col1 col2
0 1 -5
1 2 -5
2 3 -1
3 4 -1
4 5 -1
5 6 -1
这篇关于 pandas 数据框无法将值分配给切片子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文