我对 Python 中的 pandas 数据框有疑问:我有一个大数据框 df
,我将其分成两个子集,df1
和 df2
. df1
和df2
并不能构成df
的全部,它们只是df
的两个互斥子集。我想用 rpy2 在 ggplot 中绘制它,并根据它们是来自 df1
还是 df2
在图中显示变量。 ggplot2 需要一个融化的数据框,所以我必须创建一个新的数据框,其中有一列说明每个条目是来自 df1
还是 df2
,以便可以将此列传递给 ggplot .我试过这样做:
# add labels to df1, df2
df1["label"] = len(df1.index) * ["df1"]
df2["label"] = len(df2.index) * ["df2"]
# combine the dfs together
melted_df = pandas.concat([df1, df2])
现在可以绘制成:
# plot parameters from melted_df and colour them by df1 or df2
ggplot2.ggplot(melted_df) + ggplot2.ggplot(aes_string(..., colour="label"))
我的问题是是否有更简单、更快捷的方法来执行此操作。 ggplot 需要不断熔化/解熔 dfs,并且总是手动将熔化形式添加到 df 的不同子集似乎很麻烦。谢谢。
最佳答案
当然你可以通过使用简化:
df1['label'] = 'df1'
(而不是 df1["label"] = len(df1.index) * ["df1"]
。)
如果您发现自己经常这样做,为什么不创建自己的函数呢? (像这样):
plot_dfs(dfs):
for i, df in enumerate(dfs):
df['label'] = 'df%s' % i+1 # note: this *changes* df
melted_df = pd.concat(dfs)
# plot parameters from melted_df and colour them by df1 or df2
ggplot2.ggplot(melted_df) + ggplot2.ggplot(aes_string(..., colour="label"))
return # the melted_df or ggplot ?
关于python - 在 Python pandas 中拆分和连接数据帧以使用 rpy2 进行绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15053834/