fram框架变更 python_python-为什么在函数内进行此DataFrame修改会更改全局外部函数?...

这篇博客探讨了Python中pandas DataFrame的可变性特性,指出虽然DataFrame是值可变的,但大多数方法产生新的对象而不改变原始数据。通过示例展示了在函数内部对DataFrame的操作,如使用`copy()`防止对全局变量的影响。
摘要由CSDN通过智能技术生成

从docs开始:

Mutability and copying of data

All pandas data structures are value-mutable (the values they contain can be altered) but not always

size-mutable. The length of a Series cannot be changed, but, for

example, columns can be inserted into a DataFrame. However, the vast

majority of methods produce new objects and leave the input data

untouched. In general, though, we like to favor immutability where

sensible.

这是另一个示例,显示值(单元格)的可变性:

In [21]: df

Out[21]:

a b c

0 3 2 0

1 3 3 1

2 4 0 0

3 2 3 2

4 0 4 4

In [22]: df2 = df

In [23]: df2.loc[0, 'a'] = 100

In [24]: df

Out[24]:

a b c

0 100 2 0

1 3 3 1

2 4 0 0

3 2 3 2

4 0 4 4

df2是对df的引用

In [28]: id(df) == id(df2)

Out[28]: True

您的函数不会改变DF参数:

def adding_var_inside_function(df):

df = df.copy()

df['value'] = 0

return df

In [30]: df

Out[30]:

a b c

0 100 2 0

1 3 3 1

2 4 0 0

3 2 3 2

4 0 4 4

In [31]: adding_var_inside_function(df)

Out[31]:

a b c value

0 100 2 0 0

1 3 3 1 0

2 4 0 0 0

3 2 3 2 0

4 0 4 4 0

In [32]: df

Out[32]:

a b c

0 100 2 0

1 3 3 1

2 4 0 0

3 2 3 2

4 0 4 4

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值