为除除一个列之外的每个列向Row添加值

时间:2016-01-12 11:16:44

标签: python pandas insert row dataframe

我需要添加" -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

谢谢大家。

1 个答案:

答案 0 :(得分:0)

您可以对drop使用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]