Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.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_Pandas_Dataframe - Fatal编程技术网

在python中通过引用访问数据帧的一部分

在python中通过引用访问数据帧的一部分,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个大型DataFrame对象,我希望通过引用访问其中的部分,也就是说,无论何时更新原始的大型DataFrame,较小的DataFrame也会更新 由于明显的原因,创建较小部件的副本不起作用 import pandas as pd # Create a DataFrame large_df= pd.DataFrame(dict(a=range(3))) large_df 0: a 0 0 1 1 2 2 # Sample some of the DataFrame indi

我有一个大型DataFrame对象,我希望通过引用访问其中的部分,也就是说,无论何时更新原始的大型DataFrame,较小的DataFrame也会更新

由于明显的原因,创建较小部件的副本不起作用

import pandas as pd

# Create a DataFrame
large_df= pd.DataFrame(dict(a=range(3)))
large_df

0:
   a
0  0
1  1
2  2

# Sample some of the DataFrame indices.
# In this example I keep accessing the even rows of a DataFrame
# while updating it, but `sample` is, in general,
# a random list of rows.
sample=[0,2]

# Create a copy of the sampled part of the DataFrame
sub_df = large_df.loc[sample]
sub_df

1:
   a
0  0
2  2

# Modify the original DataFrame
large_df.loc[:,'b'] = range(3,6)
large_df

2:
   a  b
0  0  3
1  1  4
2  2  5

# The copy of the sampled part is kept unchanged 
sub_df

3:
   a
0  0
2  2
我找到的唯一解决方案是回到
loc
语句

# Reusing loc, the sampled part includes the modification
large_df.loc[sample]
4:
   a  b
0  0  3
2  2  5

有没有更简单的方法?

您正在寻找用作视图的数据帧子集。您需要阅读。可能就是您想要的want@ShiheZhang不,他们不想要复制,他们想要一个视图。如果你问这是否可能,简短的回答是,不。