替换熊猫数据框中的值

时间:2018-08-28 08:35:03

标签: python pandas numpy dataframe replace

我有一个熊猫数据框,我想替换值

temp2 <- gather(temp, ' ', val, -kt)
filter(temp2, val>0) %>% 
ggplot(aes(fct_rev(kt), val, fill = ` `)) + 
  geom_col(position = 'fill', color='black') +
  geom_text(aes(label = val), position = position_fill(vjust = 0.5), size=3) +
  scale_y_continuous(labels = scales::percent_format())+theme_bw()+
  labs(x='Canton', y='Percentage')+coord_flip()+     scale_fill_grey(start = 0.9, end = .5)+
  guides(fill=guide_legend(title="Label", reverse=T))

我尝试过

    itemsets = [["26"], ["51", "28", "27"], ["50"], ["8"], ["81","26", 
    15"], ["10"], ["81"]]

    support = [0.06421, 0.00123, 0.04112, 0.0112, 0.12097, 0.08123, 
    0.0021334]

    df = pd.DataFrame()
    df["itemsets"]= itemsets
    df["support"] = support

我会得到以下结果:

    df.replace("26","dog")

1 个答案:

答案 0 :(得分:0)

创建用于替换的字典,然后对get使用嵌套列表推导-如果值不匹配,则返回旧的:

d = {'26':'dog'}
df["itemsets"] = [[d.get(y, y) for y in x] for x in df['itemsets']]
print (df)
        itemsets
0          [dog]
1   [51, 28, 27]
2           [50]
3            [8]
4  [81, dog, 15]
5           [10]
6           [81]