2016-09-08 4 views
1

私はこの単純なclean_data関数を持っています。これは、入力データフレームの数値を丸めます。コードは動作しますが、なぜ動作するのか非常に困惑しています。誰も私の理解を助けることができますか?Python Pandasはどのようにテーブルのリストを処理しますか?

私が混乱した部分はこれです。 table_listはデータフレームの新しいリストなので、コードを実行した後、table_list内の各項目をフォーマットし、tablea、tableb、およびtablecは同じままにします。しかし、明らかに私は間違っています。コードを実行した後、3つのテーブルはすべて正しくフォーマットされます。何が起こっている?助けてくれてありがとう。

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) 

答えて

0

Pythonでは、データフレームまたは複雑なオブジェクトのリストは、基礎となるデータフレームを指すリファレンスの単なるリストです。たとえば、table_listの最初の要素はtableaへの参照です。したがって、clean_dataは、table_list [0]によって与えられた参照に続いて、データフレーム、すなわちtableaに直接行く。

0

最も簡単な方法は、完全にこのコードを打破することです:

# 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) 

お役に立てば幸いです。

+2

'map(lambda df:numpy.round(df、4)、table_list)'(おそらく)は、そのスクリプト全体と同じことを成し遂げていると言えるでしょうか? –

+0

これは単なる例です。実際のコードには他にも多くの詳細があります。助けてくれてありがとう。 – qqzj

関連する問題