Python 每 n 行熊猫

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25055712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:39:46  来源:igfitidea点击:

Pandas every nth row

pythonpandasresampling

提问by Mixel

Dataframe.resample() works only with timeseries data. I cannot find a way of getting every nth row from non-timeseries data. What is the best method?

Dataframe.resample() 仅适用于时间序列数据。我找不到从非时间序列数据中获取每第 n 行的方法。最好的方法是什么?

采纳答案by chrisb

I'd use iloc, which takes a row/column slice, both based on integer position and following normal python syntax.

我会使用iloc,它需要一个行/列切片,都基于整数位置和遵循正常的 python 语法。

df.iloc[::5, :]

回答by metastableB

Though @chrisb's accepted answer does answer the question, I would like to add to it the following.

虽然@chrisb 接受的答案确实回答了这个问题,但我想添加以下内容。

A simple method I use to get the nthdata or drop the nthrow is the following:

我用来获取nth数据或删除nth行的简单方法如下:

df1 = df[df.index % 3 != 0]  # Excludes every 3rd row starting from 0
df2 = df[df.index % 3 == 0]  # Selects every 3rd raw starting from 0

This arithmetic based sampling has the ability to enable even more complex row-selections.

这种基于算法的采样能够实现更复杂的行选择。

This assumes, of course, that you have an indexcolumn of ordered, consecutive, integersstarting at 0.

当然,这假设您有一index列从 0 开始的有序、连续的整数

回答by Steztric

I had a similar requirement, but I wanted the n'th item in a particular group. This is how I solved it.

我有类似的要求,但我想要特定组中的第 n 个项目。我就是这样解决的。

groups = data.groupby(['group_key'])
selection = groups['index_col'].apply(lambda x: x % 3 == 0)
subset = data[selection]

回答by cs95

There is an even simpler solution to the accepted answer that involves directly invoking df.__getitem__.

对于包含直接调用df.__getitem__.

df = pd.DataFrame('x', index=range(5), columns=list('abc'))
df

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x
4  x  x  x

For example, to get every 2 rows, you can do

例如,要获取每 2 行,您可以执行

df[::2]

   a  b  c
0  x  x  x
2  x  x  x
4  x  x  x


There's also GroupBy.first/GroupBy.head, you group on the index:

还有GroupBy.first/ GroupBy.head,你在索引上分组:

df.index // 2
# Int64Index([0, 0, 1, 1, 2], dtype='int64')

df.groupby(df.index // 2).first()
# Alternatively,
# df.groupby(df.index // 2).head(1)

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x

The index is floor-divved by the stride (2, in this case). If the index is non-numeric, instead do

索引按步幅(在本例中为 2)进行地板划分。如果索引是非数字的,请改为

# df.groupby(np.arange(len(df)) // 2).first()
df.groupby(pd.RangeIndex(len(df)) // 2).first()

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x