![](/img/trans.png)
[英]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.