[英]Accessing python variables from other python modules, which are inside a function
[英]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.