gpt4 book ai didi

python - 随机分配 pandas DataFrame 功能

转载 作者:太空宇宙 更新时间:2023-11-03 18:31:51 26 4
gpt4 key购买 nike

我正在使用 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.
}

我怎样才能做到这一点?

最佳答案

可能:

# 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())

关于python - 随机分配 pandas DataFrame 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22286310/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com