簡體   English   中英

熊貓數據框的功能和副作用

[英]Functions of pandas data frames and side effects

我想編寫一個函數,將Pandas數據框作為輸入,並僅返回平均值大於某些指定閾值的行。 該函數有效 ,但是它具有更改輸入的副作用,而我不想這樣做。

def Remove_Low_Average(df, sample_names, average_threshold=30):
    data_frame = df
    data_frame['Mean'] = np.mean(data_frame[sample_names], axis=1)
    data_frame = data_frame[data_frame.Mean > 30]
    return data_frame.reset_index(drop=True)

例:

In [7]: junk_data = DataFrame(np.random.randn(5,5), columns=['a', 'b', 'c', 'd', 'e'])
In [8]: Remove_Low_Average(junk_data, ['a', 'b', 'c'], average_threshold=0)
In [9]: junk_data.columns
Out[9]: Index([u'a', u'b', u'c', u'd', u'e', u'Mean'], dtype='object')

因此,即使在函數中從未分配過junk_data,現在其欄仍具有“均值”。 我意識到我可以用一種更簡單的方式做到這一點,但這說明了我經常遇到的一個問題,我不知道為什么。 我認為這必須是眾所周知的事情,但是我不知道如何避免這種副作用的發生。

編輯 :下面的EdChum的鏈接回答了這個問題。

@EdChum在評論中回答了這個問題:

如果您想避免修改原始內容,則基本上可以看到此頁面 ,然后通過調用.copy()進行深度復制

您不需要復制舊的數據框,只需要分配一個新列即可:)

def remove_low_average(df, sample_names, average_threshold=30):
    mean = df[sample_names].mean(axis=1)
    return df.ix[mean > average_threshold]

# then use it as:
df = remove_low_average(df, ['a', 'b'])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM