跨数据帧中各个行的数据总和

时间:2019-01-09 22:46:28

标签: python python-3.x pandas

我正在尝试创建一条规则,只要数据帧中每一行中所有数据的总和大于1,response就等于1。请看下面。

import numpy as np
import pandas as pd
df1 = pd.DataFrame(np.random.randint(0,2,size=(10, 4)), columns=list('ABCD'))
df1['Response'] = 0

df1
Out[14]: 
   A  B  C  D  Response
0  0  0  0  0         0
1  0  1  1  0         0
2  1  1  1  1         0
3  0  0  0  0         0
4  0  1  1  1         0
5  1  1  0  0         0
6  1  1  0  0         0
7  0  1  1  1         0
8  0  0  0  0         0
9  0  1  1  1         0

我的尝试:

df1['Response'] = 1 if [sum(df1[i,:]) for i in range(10)] > 1 else 0

但是我收到此错误,而不是在response列中包含三行等于零,而其余行等于1:

TypeError: unhashable type: 'slice'

任何帮助将不胜感激。谢谢。

2 个答案:

答案 0 :(得分:2)

使用WSAStartup(...); ... SOCKET maincommsock = establishconn("127.0.0.1", 69); if (maincommsock != INVALID_SOCKET) { ... closesocket(maincommsock); } ... WSACleanup(); 进行检查:设置一个上限。

clip_upper

答案 1 :(得分:0)

尝试一下(假设所有数字都是正数):

In [1]: import numpy as np
   ...: import pandas as pd
   ...: df1 = pd.read_clipboard()

In [2]: df1
Out[2]:
   A  B  C  D  Response
0  0  0  0  0         0
1  0  1  1  0         0
2  1  1  1  1         0
3  0  0  0  0         0
4  0  1  1  1         0
5  1  1  0  0         0
6  1  1  0  0         0
7  0  1  1  1         0
8  0  0  0  0         0
9  0  1  1  1         0

In [3]: df1['Response'] = df1.any(1).astype(int)

In [4]: df1
Out[4]:
   A  B  C  D  Response
0  0  0  0  0         0
1  0  1  1  0         1
2  1  1  1  1         1
3  0  0  0  0         0
4  0  1  1  1         1
5  1  1  0  0         1
6  1  1  0  0         1
7  0  1  1  1         1
8  0  0  0  0         0
9  0  1  1  1         1
相关问题