在Python pandas中分割和连接数据框以便使用rpy2绘图
我有一个关于Python中pandas数据框的问题:我有一个很大的数据框df
,我把它分成了两个子集,df1
和df2
。这两个子集df1
和df2
加起来并不等于df
,它们只是df
的两个互不重叠的部分。我想用ggplot和rpy2来绘制这个图,并根据数据来自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需要不断地进行数据框的融化和恢复,手动为df
的不同子集添加融化后的形式似乎太麻烦了。谢谢。
1 个回答
2
当然,你可以通过使用以下方法来简化:
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 ?