遍历Pandas Dataframe中的行,保持前2行固定

DataFrame

我有一个如上所示的DataFrame。有什么方法可以在每次具有行索引[0,1,2],[0,3],4]的时候创建一个新的数据帧,这意味着保持数据帧的前2行固定(在这种情况下,索引0和1)并在固定行中包括下一行。

在Python中,输出应该具有带[0,4]行的DataFrame,依此类推。

zmclub 回答:遍历Pandas Dataframe中的行,保持前2行固定

您可以这样做:

import pandas as pd

df = pd.DataFrame({'A': ['AA','BB','CC','DD','EE'],'B': ['AA','AA','BB'],'C': ['CC','DD']})

def make_new_df(row_to_keep,orig_df):
    new_df=pd.DataFrame(columns=list(orig_df))
    new_df.loc[0]=orig_df.loc[0]
    new_df.loc[1]=orig_df.loc[1]
    new_df.loc[2]=orig_df.loc[row_to_keep]
    return new_df

在调用new_df时,将要保留的行索引作为参数,以及要从中获取行的原始数据框。

,

从注释中可以看出,除了前两行外,您还希望为每行添加一个新的dataframe

new_df_dict = {}
for i in range(2,len(df)):
    new_df_dict[i] = df.iloc[[0,1,i],:]

此后,您将在new_df_dict中拥有所有新dataframes的字典,因为字典的键是新行的编号。

,

您可以使用重新索引:

df1=df.reindex[0,2]
df2=df.reindex[0,3]
etc.

如果要使用切片:

df10=df.reindex( np.r_[0,10:len(df)] )
本文链接:https://www.f2er.com/3161723.html

大家都在问