Python 如何映射数据帧中的值?

Python 如何映射数据帧中的值?,python,pandas,numpy,Python,Pandas,Numpy,这就是我正在做的。我正在尝试将其作为输出: 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]]

这就是我正在做的。我正在尝试将其作为输出:

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
,在您的情况下,这只是一行,但对于
1
,实际上有两行需要替换

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

yourary=pd.DataFrame([np.ones(x) for x in Y[0]]).fillna(0).values
yourary

Out[63]: 
array([[1., 0., 0., 0.],
       [1., 1., 1., 0.],
       [1., 1., 1., 1.],
       [0., 0., 0., 0.],
       [1., 0., 0., 0.]])
现在:

给出:

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]

您正在给
np.array
一个参数列表,即0和1。试着用括号将它们包装起来,就像您馈送给
pd.DataFrame
@HåkonT的括号一样。你能给我举个例子吗?当然,我的意思是
np.array(0,0,0,0)
应该是
np.array([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]
   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