Python 在数据帧中围绕索引进行切片的好方法
我想使用Python 在数据帧中围绕索引进行切片的好方法,python,pandas,numpy,dataframe,Python,Pandas,Numpy,Dataframe,我想使用iloc按行或列对数据帧进行切片,同时环绕超出绑定的索引。以下是一个例子: import pandas as pd df = pd.DataFrame([[1,2,3], [4,5,6], [7,8,9]],columns=['a', 'b', 'c']) #Slice the rows from 2 to 4, which the dataframe only have 3 rows print(df.iloc[2:4,:]) 数据帧: a b c 0 1
iloc
按行或列对数据帧进行切片,同时环绕超出绑定的索引。以下是一个例子:
import pandas as pd
df = pd.DataFrame([[1,2,3], [4,5,6], [7,8,9]],columns=['a', 'b', 'c'])
#Slice the rows from 2 to 4, which the dataframe only have 3 rows
print(df.iloc[2:4,:])
数据帧:
a b c
0 1 2 3
1 4 5 6
2 7 8 9
输出将是:
a b c
2 7 8 9
但是我想环绕越界索引,如下所示:
a b c
2 7 8 9
0 1 2 3
在numpy
中,可以使用numpy.take
环绕绑定外索引进行切片。()
输出为:
[[7 8 9]
[1 2 3]]
使用numpy.take
可以解决在pandas
中包装的问题:
import pandas as pd
import numpy as np
df = pd.DataFrame([[1,2,3], [4,5,6], [7,8,9]],columns=['a', 'b', 'c'])
# Get the integer indices of the dataframe
row_indices = np.arange(df.shape[0])
# Wrap the slice explicitly
wrap_slice = row_indices.take(range(2,4),axis = 0, mode='wrap')
print(df.iloc[wrap_slice, :])
输出将是我想要的输出:
a b c
2 7 8 9
0 1 2 3
我查看了
pandas.DataFrame.take
,没有“wrap”
模式。(). 解决这个问题的好方法是什么?多谢各位 让我们尝试使用np.roll
:
df.reindex(np.roll(df.index, shift=-2)[0:2])
输出:
a b c
2 7 8 9
0 1 2 3
为了让它更通用一些:
startidx = 2
endidx = 4
df.iloc[np.roll(df.index, shift=-1*startidx)[0:endidx-startidx]]
你可以用余数除法
import numpy as np
start_id = 2
end_id = 4
idx = np.arange(start_id, end_id, 1)%len(df)
df.iloc[idx]
# a b c
#2 7 8 9
#0 1 2 3
此方法实际上允许您循环多次:
start_id = 2
end_id = 10
idx = np.arange(start_id, end_id, 1)%len(df)
df.iloc[idx]
# a b c
#2 7 8 9
#0 1 2 3
#1 4 5 6
#2 7 8 9
#0 1 2 3
#1 4 5 6
#2 7 8 9
#0 1 2 3
start_id = 2
end_id = 10
idx = np.arange(start_id, end_id, 1)%len(df)
df.iloc[idx]
# a b c
#2 7 8 9
#0 1 2 3
#1 4 5 6
#2 7 8 9
#0 1 2 3
#1 4 5 6
#2 7 8 9
#0 1 2 3