首页 > 解决方案 > 如何使用不纯函数将单行从一个熊猫数据帧移动到另一个数据帧?

问题描述

所以我写了一个简短的函数,它基本上根据索引将单行从一个数据帧移动到另一个数据帧,同时保留索引。

如果我有这个测试数据框和一个空的:

df = pd.DataFrame({'lower': ['a','b','c'],
                   'upper': ['A', 'B', 'C'],
                   'number': [1, 2, 3]},
                  index=['first', 'second', 'third'])
print(df, '\n\n')

empty = pd.DataFrame(columns=['lower', 'upper', 'number'])
print(empty, '\n\n')

我只是使用说明:

line = 'second'
empty = empty.append(df.loc[line])
df = df.drop(index=line)

有用。

但是,如果我尝试编写一个做同样事情的不纯函数,它只会修改函数内部的数据帧,而在函数外部它们保持不变!?

这是我的整个代码:

def move_line(ind, source, destination):
    row = source.loc[ind]
    destination = destination.append(row)
    source = source.drop(index=ind)
    print('source inside function\n', source, '\n\n')
    print('destination inside function\n', destination, '\n\n')


def main():

    df = pd.DataFrame({'lower': ['a','b','c'],
                       'upper': ['A', 'B', 'C'],
                       'number': [1, 2, 3]},
                      index=['first', 'second', 'third'])
    #print(df, '\n\n')

    empty = pd.DataFrame(columns=['lower', 'upper', 'number'])
    #print(empty, '\n\n')


    move_line('second', df, empty)

    print('source outside function\n', df, '\n\n')
    print('destination outside function\n', empty)

标签: pythonpandasfunction

解决方案


它只修改函数内部的数据帧,而在函数外部它们保持不变!?

那是因为DataFrame.append不会改变原始 DataFrame,它会使用新行创建一个新 DataFrame。原始对象保持不变。DataFrame.drop默认情况下也不会更改原始对象,除非您通过inplace=True.

destination = destination.append(row)
source = source.drop(index=ind)

在这里,您只是将名称重新绑定到destinationandsource返回的对象appenddrop它们与destinationandsource最初指向的原始对象不同。原始对象保持不变。

要改变原始对象,您可以执行以下操作

def move_line(ind, source, destination):
    row = source.loc[ind]
    destination.loc[ind] = row 
    source.drop(index=ind, inplace=True)
    print('source inside function\n', source, '\n\n')
    print('destination inside function\n', destination, '\n\n')
df = pd.DataFrame({'lower': ['a','b','c'],
                   'upper': ['A', 'B', 'C'],
                   'number': [1, 2, 3]},
                  index=['first', 'second', 'third'])
#print(df, '\n\n')

empty = pd.DataFrame(columns=['lower', 'upper', 'number'])
#print(empty, '\n\n')


move_line('second', df, empty)

print('source outside function\n', df, '\n\n')
print('destination outside function\n', empty)

输出:

source inside function
       lower upper  number
first     a     A       1
third     c     C       3 


destination inside function
        lower upper number
second     b     B      2 


source outside function
       lower upper  number
first     a     A       1
third     c     C       3 


destination outside function
        lower upper number
second     b     B      2

推荐阅读