【问题标题】:Whether slicing of DataFrame in python return copy or reference to the original DataFrame在python中对DataFrame进行切片是返回副本还是对原始DataFrame的引用
【发布时间】:2020-10-06 02:43:30
【问题描述】:
import numpy as np
import pandas as pd
from numpy.random import randn
np.random.seed(101)

print(randn(5, 4))
df = pd.DataFrame( randn(5, 4), ['A', 'B', 'C', 'D', 'F'], ['W', 'X', 'Y', 'Z'] )

tmp_df = df['X'] 
print(type(tmp_df)) # Here type is Series (as expected)

tmp_df.loc[:] = 12.3
print(tmp_df)

print(df)

此代码更改(原始)DataFrame df 的内容。

np.random.seed(101)
print(randn(5, 4))
df = pd.DataFrame( randn(5, 4), ['A', 'B', 'C', 'D', 'F'], ['W', 'X', 'Y', 'Z'] )

tmp_df = df.loc[['A', 'B'], ['W', 'X']] 
print(type(tmp_df)) # Type is DataFrame

tmp_df.loc[:] = 12.3 # whereas, here when I change the content of the tmp_df it doesn't reflect on original array.
print(tmp_df)

print(df)

那么,这是否意味着如果我们从 DataFrame 中将 Series 切片,引用将传递给切片对象。 然而,如果它是被切片的 DataFrame,那么它不会指向原始 DataFrame。

请确认我上面的结论是否正确?我们将不胜感激。

【问题讨论】:

  • 您确定 tmp_df = df[['A', 'B'], ['W', 'X']] 部分适合您吗?
  • @LazyCoder,更新了错字。谢谢

标签: python-3.x pandas numpy dataframe numpy-slicing


【解决方案1】:

简单地说:使用loc 中的列表进行索引总是返回一个副本

让我们使用 DataFrame df:

df=pd.DataFrame({'A':[i for i in range(100)]})
df.head(3)
Output:
0   0
1   1
2   2

当我们尝试对切片数据进行操作时。

h=df.loc[[0,1,2],['A']]
h.loc[:] = 12.3
h
Output of h:
0   12.3
1   12.3
2   22.3

结果与您的情况不同:

df.head(3)
Output:
0   0
1   1
2   2

但是当你这样做tmp_df = df['X']时,系列tmp_df指的是df列中"X"的内容。当您修改 tmp_df 时,这意味着会发生变化。

【讨论】:

  • 在这里,您已经确认了我的第二个结论,即它不会影响 DataFrame df。而如果您从 DataFrame 中取出该系列,那么它会更改原始 DataFrame 中的输出,(这发生在我的第一个查询中)
  • 是的,没错,当您将列值作为系列并对其进行一些更改时,也会影响原始数据框。
猜你喜欢
  • 2017-09-28
  • 2014-05-26
  • 1970-01-01
  • 2016-09-16
  • 1970-01-01
  • 1970-01-01
  • 2017-05-21
  • 1970-01-01
  • 2021-09-27
相关资源
最近更新 更多