簡體   English   中英

python中包含全局命令的函數中的%run與復制/粘貼差異

[英]%run vs. copy/paste discrepancy in function containing global commands in python

下面是一個導入函數,用於將.csv文件讀入python。 我使用global命令創建全局變量“ data”,並將.csv文件讀入“ data”變量中,以供用戶使用。

如果我將代碼復制/粘貼到客戶端中,則可以正常工作。 但是,當我用%run“讀取”包含代碼的文件時,該函數將運行,但不會創建“ data”全局變量(例如,我調用“ data”,並得到一個錯誤)。

注意:我知道此代碼還沒有完善,但是我不確定為什么會遇到問題。

def dat():
import pandas as pd
file = raw_input('Enter your .csv file:  ')
global data
try:
    data = pd.read_csv(file)
    print "\nI've created the following variables for you: 'data' will contain your datafile that we just imported."
except:
    print "I'm so sorry, but I have no idea what just went wrong."

.csv文件中的某些數據如下所示:

Les1    Les2    Les3
2   4   4
3   3   3
1   5   3
2   4   3

test.csv

Les1,Les2,Les3
2,4,4
3,3,3
1,5,3
2,4,3

import pandas as pd

def dat():
    file = raw_input('Enter your .csv file:  ')
    global data
    try:
        data = pd.read_csv(file)
        print data
        print "\nI've created the following variables for you: 'data' will contain your datafile that we just imported."
    except:
        print "I'm so sorry, but I have no idea what just went wrong."

dat()

輸出:

Enter your .csv file:  test.csv
   Les1  Les2  Les3
0     2     4     4
1     3     3     3
2     1     5     3
3     2     4     3

I've created the following variables for you: 'data' will contain your datafile that we just imported.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM