2017-01-20 49 views
5

如果我有一個現有的熊貓數據框,是否有一種方法來生成python代碼,在另一個python腳本中執行時,將會重現該數據幀。熊貓數據幀到代碼

例如

In[1]: df 

Out[1]: 
    income user 
0 40000 Bob 
1 50000 Jane 
2 42000 Alice 

In[2]: someFunToWriteDfCode(df) 

Out[2]: 
df = pd.DataFrame({'user': ['Bob', 'Jane', 'Alice'], 
    ...:     'income': [40000, 50000, 42000]}) 
+1

你的問題沒有任何意義。在另一個程序中執行?你在說什麼?蟒蛇,R?只需將數據框保存爲csv並將其加載到其他程序中即可 –

回答

-1

您可以先保存您擁有的數據幀,然後在需要時加載另一個python腳本。你可以使用兩個軟件包:pickleshelve

要與pickle做到這一點:

import pickle 
with open('dataframe', 'rb') as pfile: 
    df2 = pickle.load(pfile)  # read the dataframe stored in file "dataframe" 
    print(df2) 

輸出:

income user 
0 40000 Bob 
1 50000 Jane 
2 42000 Alice 

要做到這一點與shelve

import pandas as pd 
import pickle 
df = pd.DataFrame({'user': ['Bob', 'Jane', 'Alice'], 
        'income': [40000, 50000, 42000]}) 
with open('dataframe', 'wb') as pfile: 
    pickle.dump(df, pfile)   # save df in a file named "dataframe" 

要在另一個文件中讀取數據框

import pandas as pd 
import shelve 
df = pd.DataFrame({'user': ['Bob', 'Jane', 'Alice'], 
        'income': [40000, 50000, 42000]}) 
with shelve.open('dataframe2') as shelf: 
    shelf['df'] = df    # store the dataframe in file "dataframe" 

要讀取另一個文件中的數據框:

import shelve 
with shelve.open('dataframe2') as shelf: 
    print(shelf['df'])    # read the dataframe 

輸出:

income user 
0 40000 Bob 
1 50000 Jane 
2 42000 Alice 
+0

這個問題非常清楚地表明'生成python代碼'。這可能有多種原因,也許是在無法訪問讀/寫文件系統的系統上運行。醃菜和擱架都不會創建Python代碼。 – madoki

1

你可以嘗試使用to_dict()方法對數據幀:

print "df = pd.DataFrame(%s)" % (str(df.to_dict())) 

如果你的數據包含NaN,你必須用float('nan')代替它們:

print "df = pd.DataFrame(%s)" % (str(df.to_dict()).replace(" nan"," float('nan')"))