繁体   English   中英

对 DataFrame 中各行的数据求和

[英]Sum Data Across Individual Rows in a DataFrame

我正在尝试创建一个规则,只要数据帧中每一行的所有数据总和大于 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列中三行等于 0,其余行等于 1:

TypeError: unhashable type: 'slice'

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

检查clip_upper :设置上限。

df.sum(1).clip_upper(1)
Out[153]: 
0    0
1    1
2    1
3    0
4    1
5    1
6    1
7    1
8    0
9    1
dtype: int64

试试这个(它假设所有的数字都是正数):

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM