繁体   English   中英

为每一列增加行值

[英]Add value to Row for every column except one

我需要将“ -1”值添加到一行中除一个单元格之外的所有单元格中。 我需要根据列的名称而不是数字来查找该名称。

示例(应该是一行):

0 | 1 | 2 | -1 | 4 |

我的代码:

for i in myRange:
    P_total.ix[i] = [-1 for n in range(len(P_total.columns))]

此代码在整个行中添加“ -1”,如何检查每个特定的列名称中是否包含“ name”字符串?

我知道如何执行此操作,但不能在for内进行:

if "name" not in exampleString:
    //any code

谢谢你们。

您可以将drop用于您的P_total.columns ,然后将其与数据P_total.columns一起使用:

np.random.seed(632)
P_total = pd.DataFrame(np.random.randn(10,5), columns=list('abcde'))

In [262]: P_total
Out[262]:
          a         b         c         d         e
0 -0.202506  1.245011   -1.787930 -1.076415
1  0.603727 -1.242478  0.430865 -1.689979  0.885975
2 -1.408643  0.545198 -1.351751 -0.095847  1.506013
3  1.454067 -1.081069 -0.162412 -0.141595 -1.180774
4 -0.578398  0.780636  0.873509 -1.373164 -0.956986
5  0.881837 -0.137655 -0.052613 -0.527390 -0.818549
6  1.401598  2.229587  0.312385 -0.009606  0.604757
7  0.286984 -0.210015  0.078443 -0.539372  1.910570
8  0.494034  1.302240  0.134238  0.741682  0.888207
9 -1.729944  0.179502 -1.386532  0.613595  0.594123

P_total.ix[0, P_total.columns.drop('c')] = -1

In [264]: P_total
Out[264]:
          a         b         c         d         e
0 -0.202506 -1.000000 -1.000000 -1.000000 -1.000000
1  0.603727 -1.242478  0.430865 -1.689979  0.885975
2 -1.408643  0.545198 -1.351751 -0.095847  1.506013
3  1.454067 -1.081069 -0.162412 -0.141595 -1.180774
4 -0.578398  0.780636  0.873509 -1.373164 -0.956986
5  0.881837 -0.137655 -0.052613 -0.527390 -0.818549
6  1.401598  2.229587  0.312385 -0.009606  0.604757
7  0.286984 -0.210015  0.078443 -0.539372  1.910570
8  0.494034  1.302240  0.134238  0.741682  0.888207
9 -1.729944  0.179502 -1.386532  0.613595  0.594123

或者,您可以通过用该列设置数据框来实现无循环运行:

P_total[P_total.columns.drop('c')] = -1

In [266]: P_total
Out[266]:
   a  b         c  d  e
0 -1 -1  0.628800 -1 -1
1 -1 -1  0.430865 -1 -1
2 -1 -1 -1.351751 -1 -1
3 -1 -1 -0.162412 -1 -1
4 -1 -1  0.873509 -1 -1
5 -1 -1 -0.052613 -1 -1
6 -1 -1  0.312385 -1 -1
7 -1 -1  0.078443 -1 -1
8 -1 -1  0.134238 -1 -1
9 -1 -1 -1.386532 -1 -1  

编辑

如果需要使用名称过滤列,则可以使用str.contains方法:

In [283]: P_total.columns
Out[283]: Index(['a', 'b', 'c', 'd', 'e'], dtype='object')

In [284]: P_total.columns.str.contains('a')
Out[284]: array([ True, False, False, False, False], dtype=bool)

然后将结果传递给ix方法的第二个字段:

your_columns = P_total.columns.str.contains('a')
P_total.ix[0, your_columns]

暂无
暂无

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

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