函数的输入对象将被返回覆盖

问题描述 投票:2回答:2

我对Python比较新,我遇到了一个函数问题。基本上这个函数应该编辑一个pandas数据帧并在新的对象名下返回它。所以保持原始对象不变。返回的对象应保存在新对象中。我的问题是,输入对象也会受到影响。即使将结果保存到新对象,如何防止输入对象受到该函数的影响。我读了一些关于不可变和可变对象的内容,但是如何更改我的功能。

import pandas as pd
import numpy as np

msg_items = pd.DataFrame({'Column_A': [10,20,30,40,50,60]})

print('Before: ', msg_items.dtypes)

def justdoit(myframe):
    cols = list(myframe)
    myframe[cols] = myframe[cols].applymap(np.str)
    return myframe

testframe = justdoit(msg_items)

print('After: ', msg_items.dtypes)

实际产量:

Before:  Column_A    int64
dtype: object
After:  Column_A    object
dtype: object

预期产量:

Before:  Column_A    int64
dtype: object
After:  Column_A    int64
dtype: object
python function pandas return
2个回答
3
投票

如果你的目标是将数据帧转换为字符串而不修改原始数据,那么你就没有做到正确,因为

myframe[cols] = myframe[cols].applymap(np.str)
  1. 将结果分配回原始数据框,以便进行更改
  2. 是不是最常用的方式来将字符串列入字符串

进一步,

return myframe

返回您刚刚分配给新变量的同一对象。只有一个数据帧,但通过两个变量访问它的两种方式!

要将数据帧转换为字符串,请使用astype(str) -

def just_do_it(df):
    return df.astype(str)

如果要编辑子集并返回副本,请调用df.copy -

def just_do_it(df, subset):
    df_new = df.copy()
    df_new[subset] = df_new[subset].astype(str)

    return df_new

new_msg_items = just_do_it(msg_items, subset=list(msg_items))
msg_items.dtypes
Column_A    int64
dtype: object

new_msg_items.dtypes
Column_A    object
dtype: object

另外,如果您有可变类型的列,则可能需要执行深度检查。在这种情况下,用copy调用deep=True -

df_new = df.copy(deep=True)

0
投票

在你的函数中 - 用copy.deepcopy(x)创建一个新对象,然后更改它上面的值并返回它。

def justdoit(myframe):
    cols = list(myframe)
    myframe_new = copy.deepcopy(myframe)
    myframe_new [cols] = myframe[cols].applymap(np.str)
    return myframe_new 
© www.soinside.com 2019 - 2024. All rights reserved.