【问题标题】:how to update crosstab values in python pandas如何更新python pandas中的交叉表值
【发布时间】:2017-08-09 15:51:41
【问题描述】:

我试图用我给出的正常噪音来改变交叉表的值。但是我更改后无法更新它。你能帮我吗?

cross_tab1 = pd.crosstab(data[0], [data[1], data[2]], rownames=['data0'], colnames=['data1', 'data2'])
c1 = cross_tab1.unstack()


for (a, b, c), count in c1.iteritems():
    count = np.round(count + np.random.normal(0, 2.0)).clip(min=0)
    cross_tab1.loc(a,b,c, int(count))

【问题讨论】:

    标签: python python-3.x pandas dataframe crosstab


    【解决方案1】:

    我认为您可以使用 loc 分配新值并持续使用 DataFrame unstack 进行转置:

    for (a, b, c), count in c1.iteritems():
        count = np.round(count + np.random.normal(0, 2.0)).clip(min=0)
        c1.loc[a,b,c] = int(count)
    
    df = c1.unstack(2).T
    

    但更好的是使用applymap:

    df1 = cross_tab1.applymap(lambda x: np.round(x + np.random.normal(0, 2.0)).clip(min=0)) \
                    .astype(int)
    

    【讨论】:

    • 谢谢。我用了applymap
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-24
    • 2017-08-03
    • 2020-08-16
    • 2020-01-11
    • 2022-07-08
    • 2020-09-01
    相关资源
    最近更新 更多