Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 分配给父数据帧会影响子数据帧吗?_Python_Python 3.x_Pandas_Copy - Fatal编程技术网

Python 分配给父数据帧会影响子数据帧吗?

Python 分配给父数据帧会影响子数据帧吗?,python,python-3.x,pandas,copy,Python,Python 3.x,Pandas,Copy,大量的SO答案澄清了对“子”数据帧的分配可能反映在“父”数据帧中,也可能不反映在“父”数据帧中(取决于某些条件) 相反的情况如何:分配给“父”数据帧是否会反映在“子”数据帧中,并且取决于完全相同的条件 我注意到当分配给“父”数据帧时,SettingWithCopywarning似乎没有出现;文件中也没有讨论这一点 df_parent = pd.DataFrame({'a': [2,2,3,3], 'b': range(4)}) df_child = df_parent[df_parent['a'

大量的SO答案澄清了对“子”数据帧的分配可能反映在“父”数据帧中,也可能不反映在“父”数据帧中(取决于某些条件)

相反的情况如何:分配给“父”数据帧是否会反映在“子”数据帧中,并且取决于完全相同的条件

我注意到当分配给“父”数据帧时,
SettingWithCopy
warning似乎没有出现;文件中也没有讨论这一点

df_parent = pd.DataFrame({'a': [2,2,3,3], 'b': range(4)})
df_child = df_parent[df_parent['a']==2]
df_child.loc[0,'a'] = 100 # `SettingWithCopy` warning
df_parent.loc[0, 'a'] = 1000 # no warning; but unclear if df_child is updated?

从文件中:

所有数据结构都是值可变的(它们包含的值 可以更改),但大小不总是可变的。系列的长度 无法更改,但是,例如,可以将列插入到 数据帧。然而,绝大多数方法都会生成新对象 并保持输入数据不变。不过,总的来说,我们喜欢 在合理的情况下支持不变性

它在两个方向上都“起作用”:

In [83]: df
Out[83]:
   a  b  c
0  0  9  5
1  9  1  5
2  7  0  0
3  3  6  9
4  4  0  8
5  4  5  8
6  1  3  6
7  4  4  9
8  6  7  4
9  2  9  6

In [84]: copy.ix[0,'a'] = 100

In [85]: copy
Out[85]:
     a  b  c
0  100  9  5
1    9  1  5
2    7  0  0
3    3  6  9
4    4  0  8
5    4  5  8
6    1  3  6
7    4  4  9
8    6  7  4
9    2  9  6

In [86]: df
Out[86]:
     a  b  c
0  100  9  5
1    9  1  5
2    7  0  0
3    3  6  9
4    4  0  8
5    4  5  8
6    1  3  6
7    4  4  9
8    6  7  4
9    2  9  6
如果您想要DF的独立副本,请使用
.copy()

In [89]: df
Out[89]:
   a  b  c
0  3  4  2
1  9  5  1
2  1  9  0

In [90]: copy = df.copy()

In [91]: df.ix[0,'a'] = 100

In [92]: df
Out[92]:
     a  b  c
0  100  4  2
1    9  5  1
2    1  9  0

In [93]: copy
Out[93]:
   a  b  c
0  3  4  2
1  9  5  1
2  1  9  0

什么是孩子?您没有在示例中定义它。@BrenBarn oops已修复。我想没有
SettingWithCopy
警告,因为父DF实际上不知道哪个子DF链接到它。