【问题标题】:Distributing a pandas DataFrame feature at random随机分发 pandas DataFrame 功能
【发布时间】:2014-03-09 18:33:52
【问题描述】:

我正在使用 pandas 读取一组数据并使用 matplotlib 进行绘制。一列是“类别”,例如“体育”、“娱乐”,但对于某些行,这被标记为“随机”,这意味着我需要分配此值并将其随机添加到一列。理想情况下,我想在数据框中执行此操作,以便分发所有值。

我的基本图形代码如下:

df.category.value_counts().plot(kind="barh", alpha=a_bar)
title("Category Distribution")

我想要的行为是

If category == "Random"{
   Assign this value to another column at random.
} 

我怎样才能做到这一点?

【问题讨论】:

    标签: python python-2.7 matplotlib pandas


    【解决方案1】:

    可能:

    # take the original value_counts, drop 'Random'
    ts1 = df.category.value_counts()
    rand_cnt = ts1.random
    ts1.drop('Random', inplace=True)
    
    # randomly choose from the other categories
    ts2 = pd.Series(np.random.choice(ts1.index, rand_cnt)).value_counts()
    
    # align the two series, and add them up
    ts2 = ts2.reindex_like(ts1).fillna(0)
    (ts1 + ts2).plot(kind='barh')
    

    如果你想修改原始数据框,那么

    idx = df.category == 'Random'
    xs = df.category[~idx].unique()  # all other categories
    
    # randomly assign to categories which are 'Random'
    df.category[idx] = np.random.choice(xs, idx.sum())
    

    【讨论】:

      猜你喜欢
      • 2017-07-10
      • 1970-01-01
      • 2019-02-05
      • 2016-09-13
      • 2018-08-13
      • 1970-01-01
      • 1970-01-01
      • 2021-01-24
      • 1970-01-01
      相关资源
      最近更新 更多