【发布时间】:2016-07-21 12:50:12
【问题描述】:
是否有一个优雅的解决方案只打印 pandas 数据帧的第 n 行?例如,我只想打印第二行。
这可以通过
i = 0
for index, row in df.iterrows():
if ((i%2) == 0):
print(row)
i++
但是有没有更 Pythonic 的方式来做到这一点?
【问题讨论】:
是否有一个优雅的解决方案只打印 pandas 数据帧的第 n 行?例如,我只想打印第二行。
这可以通过
i = 0
for index, row in df.iterrows():
if ((i%2) == 0):
print(row)
i++
但是有没有更 Pythonic 的方式来做到这一点?
【问题讨论】:
使用带有iloc 的步骤参数对df 进行切片:
print(df.iloc[::2])
In [73]:
df = pd.DataFrame(np.random.randn(5,3), columns=list('abc'))
df
Out[73]:
a b c
0 0.613844 -0.167024 -1.287091
1 0.473858 -0.456157 0.037850
2 0.020583 0.368597 -0.147517
3 0.152791 -1.231226 -0.570839
4 -0.280074 0.806033 -1.610855
In [77]:
print(df.iloc[::2])
a b c
0 0.613844 -0.167024 -1.287091
2 0.020583 0.368597 -0.147517
4 -0.280074 0.806033 -1.610855
【讨论】: