首页 > 解决方案 > 带有 for 循环和函数调用的函数

问题描述

我有一个功能如下:

def get_type(df, index):
    df_type = df[index] #so i can obtain for index 0, 1, 2.. until n-1
    return df_type

我想在一个循环遍历索引并将它们附加到列表中的函数中创建一个 for 循环,例如:

def all_df_list(df, index):
    #where index is n-1 
    list_of_df = []
    list_of_columns = []
    for i in range(index):
        df = get_type(df, i)
        list_of_df.append(df)
        list_of_df_colums(df.columns[0])

这样我就可以获得所有索引 df 及其列的列表:

get_df_and_columns = all_df_list(df, index=50)
#say we have 51 items in the df

我该如何处理这样的事情?

标签: pythonpandasdataframedata-science

解决方案


假设您有一个数据框 df 并希望它的索引和列作为列表

def all_df_list(df):
    col = df.columns.to_list()
    index = df.index.to_list()
    return (col, index)

推荐阅读