pandas 在函数内部修改的 DataFrame

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31614011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:40:47  来源:igfitidea点击:

DataFrame modified inside a function

pythonpandas

提问by Alexis G

I face to a modification of a dataframe inside a function that I have never observed previously. Is there a method to deal with this and no modify the initial dataframe ?

我在以前从未观察过的函数中修改了数据框。有没有办法解决这个问题而不修改初始数据帧?

In[30]: def test(df):
    df['tt'] = np.nan
    return df

In[31]: dff = pd.DataFrame(data=[])

In[32]: dff

Out[32]: 
Empty DataFrame
Columns: []
Index: []
In[33]: df = test(dff)

In[34]: dff

Out[34]: 
Empty DataFrame
Columns: [tt]
Index: []

回答by Skorpeo

def test(df):
    df = df.copy(deep=True)
    df['tt'] = np.nan
    return df

If you pass the dataframe into a function and manipulate it and return the same dataframe, you are going to get the same dataframe in modified version. If you want to keep your old dataframe and create a new dataframe with your modifications then by definition you have to have 2 dataframes. The one that you pass in that you don't want modified and the new one that is modified. Therefore, if you don't want to change the original dataframe your best bet is to make a copy of the original dataframe. In my example I rebound the variable "df" in the function to the new copied dataframe. I used the copy method and the argument "deep=True" makes a copy of the dataframe and its contents. You can read more here:http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.copy.html

如果您将数据帧传递给函数并对其进行操作并返回相同的数据帧,您将获得修改版本的相同数据帧。如果您想保留旧数据框并通过修改创建新数据框,那么根据定义,您必须有 2 个数据框。您传入的不想修改的和修改的新的。因此,如果您不想更改原始数据帧,最好的办法是制作原始数据帧的副本。在我的示例中,我将函数中的变量“df”重新绑定到新复制的数据帧。我使用了 copy 方法,参数“deep=True”制作了数据帧及其内容的副本。您可以在此处阅读更多信息:http: //pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.copy.html