【问题标题】:splitting and concatenating dataframes in Python pandas for plotting with rpy2在 Python pandas 中拆分和连接数据帧以使用 rpy2 进行绘图
【发布时间】:2013-02-09 19:42:41
【问题描述】:

我有一个关于 Python 中的 pandas 数据框的问题:我有一个大数据框 df,我将它分成两个子集,df1df2df1df2 一起并不能构成 df 的全部,它们只是它的两个互斥子集。我想用 rpy2 在 ggplot 中绘制它,并根据它们来自df1df2 在图中显示变量。 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"] = len(df1.index) * ["df1"] 替换为df1["label"] = "df1"

标签: python numpy pandas rpy2


【解决方案1】:

当然,您可以使用以下方法进行简化:

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 ?

【讨论】:

  • 既然函数被称为plot_dfs,我会说返回ggplot对象。
猜你喜欢
  • 2023-04-02
  • 2015-04-05
  • 2013-01-17
  • 2012-08-15
  • 1970-01-01
  • 1970-01-01
  • 2014-04-15
  • 2022-09-23
  • 2022-06-21
相关资源
最近更新 更多