如何更新 python pandas 中的交叉表值

how to update crosstab values in python pandas

我试图用我给出的正常噪音改变交叉表的值。但是我改了之后就更新不了了。你能帮我吗?

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

我认为您可以使用 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)