python - 如何使用不纯函数将单行从一个熊猫数据帧移动到另一个数据帧?
问题描述
所以我写了一个简短的函数,它基本上根据索引将单行从一个数据帧移动到另一个数据帧,同时保留索引。
如果我有这个测试数据框和一个空的:
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)
解决方案
它只修改函数内部的数据帧,而在函数外部它们保持不变!?
那是因为DataFrame.append
不会改变原始 DataFrame,它会使用新行创建一个新 DataFrame。原始对象保持不变。DataFrame.drop
默认情况下也不会更改原始对象,除非您通过inplace=True
.
destination = destination.append(row) source = source.drop(index=ind)
在这里,您只是将名称重新绑定到destination
andsource
返回的对象append
,drop
它们与destination
andsource
最初指向的原始对象不同。原始对象保持不变。
要改变原始对象,您可以执行以下操作
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
推荐阅读
- android - 如何使用导航架构组件创建 BottomSheetDialogFragment?
- python - Django:如何在我的登录页面上实现一个记住我的键
- r - geom_raster 给出“条纹”结果
- reactjs - React 是使用类名管理多个主题的好方法吗?
- python - 如何获取 GitHub 存储库的贡献者总数?
- java - 在 macOS 上通过 brew 安装 JRE(但不是 JDK)
- angular7 - 如何将数据传递给自定义组件的标记?
- javascript - 如何禁用具有以逗号分隔的多个值的选项?
- android - Android WebView - 滚动条不填充 layout_height
- uinavigationcontroller - 如何从导航控制器中找到可见的 pushViewController?