Skip to main content
 首页 » 编程设计

python之过滤 Pandas 数据框和覆盖不会改变数据框

2025年05月04日16mq0036

我试图对两个数据帧执行相同的操作(过滤),但由于某种原因,数据帧没有改变。我怀疑这与数据框的 View 与副本问题有关,但我无法找到解决该问题的答案。

这是重现该问题的简化代码:

In [1]: 
  import pandas as pd 
  df1 = pd.DataFrame(data = [(1,2,3),(4,5,6),(7,'a',9)], columns = ['a','b','c']) 
  df2 = pd.DataFrame(data = [(1,2,3),(4,'a',6),(7,8,9)], columns = ['a','b','c']) 
  dataframes  = [df1, df2] 
 
  for df in dataframes: 
    df = df[(df.b != 'a') & (df.c > 5)] 
    print df 
 
Out[1]: 
     a  b  c 
  1  4  5  6 
 
     a  b  c 
  2  7  8  9 
 
In [2]: 
  for df in dataframes: 
    print df 
 
Out[2]: 
    a  b  c 
  0  1  2  3 
  1  4  5  6 
  2  7  a  9 
 
     a  b  c 
  0  1  2  3 
  1  4  a  6 
  2  7  8  9 

请您参考如下方法:

在 Python 中 variable names are bound to values . 赋值语句不修改值,它们将变量名重新绑定(bind)到新值。

例如,当您像这样使用 for-loop 时:

for df in dataframes: 

Python 将 dataframes 中的值绑定(bind)到变量名 df(循环的每次迭代的新值)。 作业

df = df[(df.b != 'a') & (df.c > 5)] 

只是重新绑定(bind) df 到一个新值。它对 dataframes 没有影响。

要更改 dataframes 的值,您可以使用 list comprehension构建一个新列表并将 dataframes 分配给这个新列表:

dataframes = [df[(df.b != 'a') & (df.c > 5)] for df in dataframes] 

import pandas as pd 
df1 = pd.DataFrame(data = [(1,2,3),(4,5,6),(7,'a',9)], columns = ['a','b','c']) 
df2 = pd.DataFrame(data = [(1,2,3),(4,'a',6),(7,8,9)], columns = ['a','b','c']) 
dataframes  = [df1, df2] 
 
dataframes = [df[(df.b != 'a') & (df.c > 5)] for df in dataframes] 
for df in dataframes: 
    print(df) 

产量

   a  b  c 
1  4  5  6 
   a  b  c 
2  7  8  9