Python Pandas如何处理表格列表?

2024-09-30 03:24:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的clean_data函数,它将对输入数据帧中的数字进行四舍五入。代码可以工作,但我很困惑它为什么能工作。有人能帮我理解吗?在

我感到困惑的地方是这个。table_list是一个新的数据帧列表,因此在运行代码之后,table_list中的每一项都应该被格式化,而tablea、tableb和tablec应该保持不变。但显然我错了。运行代码后,所有三个表的格式都正确。怎么回事?非常感谢你的帮助。在

table_list = [tablea, tableb, tablec]

def clean_data(df):

    for i in df:
        df[i] = df[i].map(lambda x: round(x, 4))

    return df

map(clean_data, table_list)

Tags: 数据函数代码cleanmapdf列表data
2条回答

最简单的方法是完全分解这些代码:

# List of 3 dataframes
table_list = [tablea, tableb, tablec]

# function that cleans 1 dataframe
# This will get applied to each dataframe in table_list
# when the python function map is used AFTER this function
def clean_data(df):

    # for loop.
    # df[i] will be a different column in df for each iteration
    # i iterates througn column names.
    for i in df:
        # df[i] = will overwrite column i
        # df[i].map(lambda x: round(x, 4)) in this case
        # does the same thing as df[i].apply(lambda x: round(x, 4))
        # in other words, it rounds each element of the column
        # and assigns the reformatted column back to the column
        df[i] = df[i].map(lambda x: round(x, 4))

    # returns the formatted SINGLE dataframe
    return df

# I expect this is where the confusion comes from
# this is a python (not pandas) function that applies the
# function clean_df to each item in table_list
# and returns a list of the results.
# map was also used in the clean_df function above.  That map was
# a pandas map and not the same function as this map.  There do similar
# things, but not exactly.
map(clean_data, table_list)

希望有帮助。在

在Python中,数据帧或任何复杂对象的列表只是指向底层数据帧的引用列表。例如,table_list的第一个元素是对tablea的引用。因此,clean_数据将直接进入数据帧,即tablea,遵循table_list[0]给出的参考。在

相关问题 更多 >

    热门问题