【问题标题】:dataframe argument being changed by a function. How to avoid it being mutated?数据框参数被函数更改。如何避免它被变异?
【发布时间】:2020-04-30 10:05:54
【问题描述】:

我知道 pandas 数据框是可变的。

我将一个数据框传递给一个函数,我不希望更改原始数据框,但确实如此。 我想只要我重新分配数据框变量并避免使用 .drop(inplace=True) 和 .reset_index(inplace=True) 就可以了,但事实并非如此。
.dropna() 和 .reset_index() 有什么解决方法可以避免我的原始数据帧被变异?

谢谢。

def makeChoice():
    return bool(random.getrandbits(1))
def makeChange(row,choice):
    if choice==True:
        result = row['b']
    else:
        result = np.nan
    return result    
workingDF['b']= workingDF.apply(lambda row: makeChange(row, makeChoice()), axis=1)
workingDF = workingDF.dropna()
workingDF = workingDF.reset_index(drop=True)
return workingDF    
a = pd.DataFrame({'a':[1,2], 'b':[3,4]})
print('a - original:')
print(a)
b = testFunc3(a)
print('b after testFunc3():')
print(b)
print('a after testFunc3():')
print(a)

这给出了以下输出:

a - original:
   a  b
0  1  3
1  2  4
b after testFunc3():
   a    b
0  1  3.0
a after testFunc3():
   a    b
0  1  3.0
1  2  NaN

【问题讨论】:

    标签: python pandas dataframe mutability


    【解决方案1】:

    如果您不想修改函数内部的方法,可以将数据帧的副本发送到函数:

    b = testFunc3(a.copy())
    

    【讨论】:

      猜你喜欢
      • 2018-01-17
      • 2016-03-25
      • 2015-03-20
      • 2014-10-13
      • 1970-01-01
      • 2015-03-28
      • 1970-01-01
      • 1970-01-01
      • 2017-10-19
      相关资源
      最近更新 更多