我需要使用pandas显示第n行和最后一行。我知道可以使用iloc
显示第n行例如:
data = {"x1": [1,2,3,4,5,6,7,8,9,10], "x2": ["a","b","c","d","e","f","g","h","i","j"]}
df = pd.DataFrame(data=data)
a = df.iloc[::2]
print(a)
将显示
x1 x2
0 1 a
2 3 c
4 5 e
6 7 g
8 9 i
但我需要它:
x1 x2
0 1 a
2 3 c
4 5 e
6 7 g
8 9 i
9 10 j
如何实现?
答案 0 :(得分:2)
使用union
个索引,如果默认为loc
,则按RangeIndex
选择:
a = df.loc[df.index[::2].union([df.index[-1]])]
print(a)
x1 x2
0 1 a
2 3 c
4 5 e
6 7 g
8 9 i
9 10 j
<强>详细强>:
print(df.index[::2].union([df.index[-1]]))
Int64Index([0, 2, 4, 6, 8, 9], dtype='int64')
另一种更通用的解决方案:
data = {"x1": [1,2,3,4,5,6,7,8,9,10], "x2": ["a","b","c","d","e","f","g","h","i","j"]}
df = pd.DataFrame(data=data, index=[0]*10)
print (df)
x1 x2
0 1 a
0 2 b
0 3 c
0 4 d
0 5 e
0 6 f
0 7 g
0 8 h
0 9 i
0 10 j
arr = np.arange(len(df.index))
a = df.iloc[np.union1d(arr[::2], [arr[-1]])]
print(a)
x1 x2
0 1 a
0 3 c
0 5 e
0 7 g
0 9 i
0 10 j