gpt4 book ai didi

python - 使用列表中的索引值从大型数据帧创建较小的数据帧

转载 作者:太空宇宙 更新时间:2023-11-04 11:06:39 24 4
gpt4 key购买 nike

我有一个 list

a = [15, 50 , 75]

使用上面的列表,我必须创建更小的数据帧来过滤掉主数据帧索引上的行(行数由列表定义)。

假设我的主要数据框是 df我想要的数据帧是df1(来自行索引 0-15)、df2(来自行索引 15-65)、df3(来自行索引 65 - 125)

因为这只是三个,我可以很容易地使用下面这样的东西:

limit1 = a[0]
limit2 = a[1] + limit1
limit3 = a[2] + limit3

df1 = df.loc[df.index <= limit1]
df2 = df.loc[(df.index > limit1) & (df.index <= limit2)]
df2 = df2.reset_index(drop = True)
df3 = df.loc[(df.index > limit2) & (df.index <= limit3)]
df3 = df3.reset_index(drop = True)

但是如果我想在主数据框 df 上用一个长列表来实现它,我正在寻找像下面这样可迭代的东西(这是行不通的):

df1 = df.loc[df.index <= limit1]
for i in range(2,3):
for j in range(2,3):
for k in range(2,3):
df[i] = df.loc[(df.index > limit[j]) & (df.index <= limit[k])]
df[i] = df[i].reset_index(drop=True)
print(df[i])

最佳答案

您可以通过从主数据帧构建数据帧,迭代地从数据帧末尾切出切片来修改您的代码。

dfs = [] # this list contains your partitioned dataframes
a = [15, 50 , 75]
for idx in a[::-1]:
dfs.insert(0, df.iloc[idx:])
df = df.iloc[:idx]
dfs.insert(0, df) # add the last remaining dataframe
print(dfs)

另一种选择是使用列表表达式,如下所示:

a = [0, 15, 50 , 75]
dfs = [df.iloc[a[i]:a[i+1]] for i in range(len(a)-1)]

关于python - 使用列表中的索引值从大型数据帧创建较小的数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59286779/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com