将 Pandas DataFrame 切片为新的 DataFrame

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44966861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:56:24  来源:igfitidea点击:

Slicing a Pandas DataFrame into a new DataFrame

pythonpandascopyslice

提问by Pietro Marchesi

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.

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

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

从这个答案来看,选择.loc使用布尔数组会给我一个副本,但是,如果我尝试更改副本,SettingWithCopyWarning就会妨碍我。那么这是否是正确的方法:

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

回答by jezrael

You need copywith boolean indexing, new DataFrameconstructor is not necessary:

您需要copywith boolean indexing,不需要新的DataFrame构造函数:

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

Explanation of warning:

警告说明:

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

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