[英]Pandas dataframe get all rows between zero(0) of mask column and get first and last row of each group
[英]How to slice rows between first and last row in pandas dataframe?
我如何使用loc
將以下 pandas DataFrame
第一行和最后一行之間的所有內容切片?
輸入:
id text
0 A
1 B
2 C
3 D
輸出:
| id | text |
|----|------|
| 1 | B |
| 2 | C |
用
df.iloc[1:-1] # similar to df.iloc[1:3]
id text
1 1 B
2 2 C
按 0 到 -1(不包括)之間的位置對所有行進行切片。
由於iloc
需要位置值,如果您需要重新分配,請以這種方式將列位置作為第二個參數傳遞:
df.iloc[1:-1, df.columns.get_loc('text')] = 'Test'
df
id text
0 0 A
1 1 Test
2 2 Test
3 3 D
由於您的索引值是數字,您可以簡化上述選項(作為特例):
df.loc[1:2, 'text'] = 'Test' # note the slice is `1:2`, not `1:3` or `1:-1`
在loc
的情況下,結束切片是包含的。 如果您在運行時不知道索引標簽是什么,您可以使用以下方法進行概括:
# Generalized solution
df.loc[df.index[1]:df.index[-2], 'text'] = 'Test'
上面的解決方案將 NaN 留給未分配的行。 要將值分配給所有行,一種選擇是使用上述解決方案中的fillna
。 但是我們可以使用np.where
或更具體的表達式來優化一下,這取決於您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.