调用外部脚本

时间:2019-01-22 17:38:42

标签: python pandas

我有一长串需要针对pandas DataFrame运行的pandas转换命令:

pd['newvar_A'] = pd['somevar'] * pd['somevar']
pd['newvar_C'] = pd['somevar'] * pd['somevar']
pd['newvar_D'] = pd['somevar'] * pd['somevar']
pd['newvar_ETC'] = pd['somevar'] * pd['somevar']

这是一个很长的列表(大约150行)。是否可以在已经存在的脚本中将其作为名为transformations.py的单独脚本包含在内?这个想法是使主脚本保持简单,所以我的想法是使脚本看起来像这样:

import pandas as pd
pd.read_csv ('data.csv')
...
#Run transformations
insert file = "transformations.py"
...
#rest of the main script

是否有一个Python命令调用另一个Python脚本(假设此脚本与工作目录位于同一文件夹中)?

谢谢!

1 个答案:

答案 0 :(得分:1)

根据此post

,您可以尝试“导入”脚本,因为这是最好的方法

一个小例子

sample.csv

name,age
sharon,12
shalom,10

我要导入的脚本
nameChange.py

import pandas as pd

# transform the csv file
data = pd.read_csv('sample.csv')
data.iloc[0,0] = 'justin'
data.to_csv('sample.csv',index = False)

主要代码
stackoverflow.py

import pandas as pd

# before transform
data = pd.read_csv('sample.csv')
print(data)

# call the script
import nameChange

# do the work after the script runs
transformed_data = pd.read_csv('sample.csv')
print(transformed_data)

输出

  name  age
0 sharon 12
1 shalom 10
  name  age
0 justin 12
1 shalom 10

要运行上述代码而不修改原始的csv

我要导入的脚本
nameChange.py

import pandas as pd
import pickle

# transform the csv file variable which was saved by stackoverflow.py
data = pickle.load(open('data.sav','rb'))
data.iloc[0,0] = 'justin'
# saving the df
pickle.dump(data,open('data.sav','wb'))

主要代码
stackoverflow.py

import pandas as pd
import pickle

# before transform
data = pd.read_csv('sample.csv')
print(data)
pickle.dump(data,open('data.sav','wb'))

# call the script
import nameChange
transformed_data = pickle.load(open('data.sav','rb'))

# do the work after the script runs
print(transformed_data)