Skip to main content
 首页 » 编程设计

python之为什么无法从 Python 的 apply 函数内部访问其他变量

2025年05月04日34jpfss

为什么下面的代码不会影响Output DataFrame? (这个例子本身并不有趣——它是一种“复制”DataFrame 的复杂方式。)

def getRow(row): 
     Output.append(row) 
 
Output = pd.DataFrame() 
Input = pd.read_csv('Input.csv') 
Input.apply(getRow) 

有没有一种方法可以使用 apply 函数来获得这样的功能,从而影响其他变量?

请您参考如下方法:

发生了什么

DataFrame.append() 返回一个新的数据框。它不会修改 Output,而是每次都创建一个新的输出。

   DataFrame.append(self, other, ignore_index=False, verify_integrity=False) 

Append rows of other to the end of this frame, returning a new object. Columns not in this frame are added as new columns.

这里:

Output.append(row) 

您创建了一个新数据框,但立即将其丢弃。

您可以访问 - 但您不应该以这种方式使用它

虽然这可行,但我强烈建议不要使用 global:

df = DataFrame([1, 2, 3]) 
df2 = DataFrame() 
 
def get_row(row): 
    global df2 
    df2 = df2.append(row) 
 
df.apply(get_row) 
print(df2) 

输出:

   0  1  2 
0  1  2  3 

以此作为演示会发生什么。不要在您的代码中使用它。