Pandas Dataframe Slice using iloc or ix



我正在尝试找到一种更好的方法来分开具有可变数量列数的数据框架。我曾尝试使用ILOC和IX方法,但实际上,我正在为许多数据范围编写以下内容。有一种更好的方法来速记吗?

df.iloc[:, [0,1,2,3,4,5,6,7,8,9,10,11]] #df.ix works this way as well

我想做的是下面...

df.iloc[:, [0:df.shape[1]/2] #this will allow column number flexibility

你们中的任何一个人对此有很好的解决方案吗?

就像斯科特在评论中提到的那样,请勿使用 ix,因为它已弃用。尽管ix现在可以使用,但它可能不会将来使用,请改用iloc

但是,尝试使用numpy中的array_split()。这是非常可读的。这将均匀地将数据框分为一半(array_split将允许数字不均匀,并尽可能接近一半):

import numpy as np
df_split = np.array_split(df, 2)
# This will return a list of dataframes.
# if you need single datframes you could always use df_split[0] for first half
# and df_split[1] for other half

如果您还需要分开列,也可以做:

df_split = np.array_split(df.columns, 2) # <--- Notice the df.columns in the argument
first_half = df[df_split[0].tolist()]
second_half = df[df_split[1].tolist()]

最新更新