pandas数据框的函数及副作用

0 投票
2 回答
1155 浏览
提问于 2025-04-18 13:28

我想写一个函数,这个函数可以接收一个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在它的列中有了'Mean'这个字段,尽管这个字段在函数中并没有被赋值。我意识到我可以用更简单的方法来做到这一点,但这说明了我经常遇到的一个问题,我搞不清楚为什么会这样。我觉得这应该是个大家都知道的事情,但我不知道怎么才能让这个副作用停止发生。

编辑:EdChum下面的链接回答了这个问题。

2 个回答

0

你不需要复制旧的数据表,只要别给它新加一列就行了 :)

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'])
0

@EdChum在评论中回答了这个问题:

可以查看 这个页面,简单来说,如果你想避免修改原始数据,就可以通过调用 .copy() 来进行深拷贝。

撰写回答