将 Pandas DataFrame 切片成新的 DataFrame

Slicing a Pandas DataFrame into a new DataFrame(将 Pandas DataFrame 切片成新的 DataFrame)
本文介绍了将 Pandas DataFrame 切片成新的 DataFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用布尔索引对 DataFrame 进行切片以获得副本,然后在该副本上独立于原始 DataFrame 执行操作.

I would like to slice a DataFrame with a Boolean index obtaining a copy, and then do stuff on that copy independently of the original DataFrame.

从这个 answer 判断,使用布尔数组使用 .loc 进行选择会给我返回一个副本,但是,如果我尝试更改副本,SettingWithCopyWarning 会妨碍.那么这是否是正确的方法:

Judging from this answer, selecting with .loc using a Boolean array will hand me back a copy, but then, if I try to change the copy, SettingWithCopyWarning gets in the way. Would this then be the correct way:

import numpy as np
import pandas as pd
d1 = pd.DataFrame(np.random.randn(10, 5), columns=['a', 'b', 'c', 'd', 'e'])
# create a new dataframe from the sliced copy
d2 = pd.DataFrame(d1.loc[d1.a > 1, :])
# do stuff with d2, keep d1 unchanged

推荐答案

你需要copyboolean indexing,不需要新的DataFrame构造函数:

d2 = d1[d1.a > 1].copy()

警告说明:

如果您稍后修改 d2 中的值,您会发现修改不会传播回原始数据 (d1),并且 Pandas 会发出警告.

If you modify values in d2 later you will find that the modifications do not propagate back to the original data (d1), and that Pandas does warning.

这篇关于将 Pandas DataFrame 切片成新的 DataFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)