再次,我對Notebook和新興的rmagic基礎設施感到非常開心,但是我還有一個關於兩者之間橋樑的問題。目前我正試圖將幾個pandas DataFrame的子集傳遞給R,以便使用ggplot2進行可視化。爲了清楚起見,我知道我可以傳遞整個DataFrame並在R中執行額外的子集。然而,我的首選是利用Python的數據管理功能,並且我正在執行的子集智能操作更簡單快捷使用熊貓比在R中的等效操作。所以爲了效率和病態的好奇... ...%Rpush >>複雜對象列表(例如IPython Notebook中的pandas DataFrames)
我一直在試圖找出是否有辦法一次推動幾個對象。皺紋是有時我不知道需要推送多少物品。爲了保持靈活性,我一直在整個腳本的前端使用DataFrame填充字典。下面的代碼提供什麼,我通過工作(我還沒有通過com.convert_to_r_dataframe轉化爲簡單起見,但我真正的代碼確實需要這一步)的合理傳真:
import pandas as pd
from pandas import DataFrame
%load_ext rmagic
d1=DataFrame(np.arange(16).reshape(4,4))
d2=DataFrame(np.arange(20).reshape(5,4))
d_list=[d1,d2]
names=['n1','n2']
d_dict=dict(zip(names,d_list))
for name in d_dict.keys():
exec '%s=d_dict[name]' % name
%Rpush n1
可以看到,我可以分配一個靜態名稱,並將DataFrame單獨推入到R名稱空間中(以及在'list'>>%Rpush n1 n2中)。我不能做的是類似如下:
for name in d_dict.keys():
%Rpush d_dict[name]
片斷代碼將引發異常>> KeyError異常:u'd_dict [名]」。我也試過在列表中存入的動態命名DataFrames,列表的引用最終指向的數據,而不是對象引用:當我通過列表內容中環
df_list=[]
for name in d_dict.keys():
exec '%s=d_dict[name]' % name
exec 'df_list.append(%s)' % name
print df_list
for df in df_list:
%Rpush df
[ 0 1 2 3
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
3 12 13 14 15,
0 1 2 3
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
3 12 13 14 15
4 16 17 18 19]
%RPUSH沒有拋出異常,但在R命名空間中找不到DataFrame。除了討論將列表轉換爲R向量之外,我還沒有找到關於這個主題的大量討論。任何幫助將不勝感激!
的同一個實例,感謝(提示)響應。我會直接整合rpy2。 –