How does Python Pandas process a list of tables?
<p>I have this simple clean_data function, which will round the numbers in the input data frame. The code works, but I am very puzzled why it works. Could anybody help me understand?</p>

<p>The part where I got confused is this. table_list is a new list of data frame, so after running the code, each item inside table_list should be formatted, while tablea, tableb, and tablec should stay the same. But apparently I am wrong. After running the code, all three tables are formatted correctly. What is going on? Thanks a lot for the help.</p>

<pre><code>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)
</code></pre>

<p>Simplest way is to break down this code completely:</p>

<pre><code># 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)
</code></pre>

<p>Hope that helps.</p>

python pandas