繁体   English   中英

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

[英]Why is it not possible to access other variables from inside the apply function in Python?

为什么以下代码不会影响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 ,而是每次都创建一个新的Output

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

other行附加到该帧的末尾,返回一个新对象。 不在此框架中的列将作为新列添加。

这里:

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

以此作为示范。 不要在您的代码中使用它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM