[英]pandas dataframe fails to assign value to slice subset
我正在嘗試更改片中除第一個以外的所有值,但它不起作用...我在做什么錯?
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
的條件。 這是一個最小的示例:
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
選擇時存在連接布爾索引(過濾)的問題,一種可能的解決方案是添加新的條件:
test.index = pd.to_datetime(test.index)
mask = (test.col_1==-5)&(test.index>'2018-07-17 13:00:00')&(test.index<'2018-07-17 14:00:00')
m1 = np.arange(len(test)) > 1
test.loc[mask & m1, 'col_1']=-1
print (test)
col_1
2018-07-17 13:51:00 -5
2018-07-17 13:52:00 -1
2018-07-17 13:53:00 -1
2018-07-17 13:54:00 -1
2018-07-17 13:55:00 -1
2018-07-17 13:56:00 -1
2018-07-17 13:57:00 -1
2018-07-17 13:58:00 -1
2018-07-17 13:59:00 -1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.