gpt4 book ai didi

python - 如何在 pandas DataFrame 中映射值?

转载 作者:太空狗 更新时间:2023-10-30 02:51:39 25 4
gpt4 key购买 nike

import numpy as np
import pandas as pd


Y = pd.DataFrame(np.array([1, 3, 4, 0, 1]))

print(Y)

Y[Y[0]] = np.array(0, 0, 0, 0)
Y[Y[1]] = np.array(1, 0, 0, 0)
Y[Y[2]] = np.array(1, 1, 0, 0)
Y[Y[3]] = np.array(1, 1, 1, 0)
Y[Y[4]] = np.array(1, 1, 1, 1)

print(Y)

这就是我正在做的。我正在尝试获得输出:

[[1 0 0 0], [1 1 1 0], [1 1 1 1], [0 0 0 0], [1 0 0 0]]

但是,相反,我得到一个错误:

    Y[Y[0]] = np.array(0, 0, 0, 0)
ValueError: only 2 non-keyword arguments accepted

我做错了什么?

最佳答案

我解释你的问题的方式是用 [0, 0, 0, 0] 填充例如 0 匹配的所有 DataFrame 行,在你的情况下它只是一行,但是对于1,实际上有两行应该被替换。

我已改为使用字母而不是数字,以便于查看:

# Initialize DataFrame with zeros:
Y = pd.DataFrame(np.zeros((5,4), dtype=int), index=list('bdeab'))

现在:

print(Y)

给出:

   0  1  2  3
b 0 0 0 0
d 0 0 0 0
e 0 0 0 0
a 0 0 0 0
b 0 0 0 0

如果我们现在这样做:

mapping = {
'a': [0, 0, 0, 0],
'b': [1, 0, 0, 0],
'c': [1, 1, 0, 0],
'd': [1, 1, 1, 0],
'e': [1, 1, 1, 1]
}

for row in pd.unique(Y.index):
Y.loc[row, :] = mapping[row]

我们得到了想要的 DataFrame:

   0  1  2  3
b 1 0 0 0
d 1 1 1 0
e 1 1 1 1
a 0 0 0 0
b 1 0 0 0

关于python - 如何在 pandas DataFrame 中映射值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54948019/

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