在 pandas col 中将每第二行乘以 -1

时间:2021-02-16 07:26:39

标签: python pandas

我试图将每 2 行乘以 -1,但仅在指定的列中。使用下面的方法,我希望将 c 列中的每 2 行乘以 -1。

df = pd.DataFrame({  
    'a' : [2.0,1.0,3.5,2.0,5.0,3.0,1.0,1.0],
    'b' : [1.0,-1.0,3.5,3.0,4.0,2.0,3.0,2.0],     
    'c' : [2.0,2.0,2.0,2.0,-1.0,-1.0,-2.0,-2.0],                  
    })

df['c'] = df['c'][::2] * -1

预期输出:

     a    b    c
0  2.0  1.0  2.0
1  1.0 -1.0 -2.0
2  3.5  3.5  2.0
3  2.0  3.0 -2.0
4  5.0  4.0 -1.0
5  3.0  2.0  1.0
6  1.0  3.0 -2.0
7  1.0  2.0  2.0

5 个答案:

答案 0 :(得分:5)

使用 pandas.DataFrame.update 的一种方式:

df.update(df['c'][1::2] * -1)
print(df)

输出:

     a    b    c
0  2.0  1.0  2.0
1  1.0 -1.0 -2.0
2  3.5  3.5  2.0
3  2.0  3.0 -2.0
4  5.0  4.0 -1.0
5  3.0  2.0  1.0
6  1.0  3.0 -2.0
7  1.0  2.0  2.0

答案 1 :(得分:3)

使用 DataFrame.iloc 进行切片,Index.get_loc 用于列 c 的位置:

df.iloc[1::2, df.columns.get_loc('c')] *= -1
#working same like
#df.iloc[1::2, df.columns.get_loc('c')] = df.iloc[1::2, df.columns.get_loc('c')] * -1

或者将 DataFrame.locdf.index 中的选择值一起使用:

df.loc[df.index[1::2], 'c'] *= -1

或者:

df.loc[df.index % 2 == 1, 'c'] *= -1

print (df)
    
     a    b    c
0  2.0  1.0  2.0
1  1.0 -1.0 -2.0
2  3.5  3.5  2.0
3  2.0  3.0 -2.0
4  5.0  4.0 -1.0
5  3.0  2.0  1.0
6  1.0  3.0 -2.0
7  1.0  2.0  2.0

答案 2 :(得分:0)

或者你可以编写自己的函数:

def multiple(df):
    new_df = pd.DataFrame()
    for i in range(0, len(df)):
        if i // 2 == 0:
            new_row = pd.DataFrame(data = df.iloc[i]*(-1)).T      
            new_df = new_df.append(new_row, ignore_index=True)
        else:
            new_row = pd.DataFrame(data = df.iloc[i]).T      
            new_df = new_df.append(new_row, ignore_index=True)            

        i+=1
        
    return new_df

答案 3 :(得分:0)

您可以将 divmod 与系列一起使用:

           0            i=5
         0 1 0          i=4
       0 1 2 1 0        i=3
     0 1 2 3 2 1 0      i=2
   0 1 2 3 4 3 2 1 0    i=1
 0 1 2 3 4 5 4 3 2 1 0  i=0
   0 1 2 3 4 3 2 1 0    i=1
     0 1 2 3 2 1 0      i=2
       0 1 2 1 0        i=3
         0 1 0          i=4
           0            i=5

答案 4 :(得分:0)

您可以使用此代码:

s = 2*np.arange(len(df))%2 - 1
df["c"] = -df.c*s

     a    b    c
0  2.0  1.0  2.0
1  1.0 -1.0 -2.0
2  3.5  3.5  2.0
3  2.0  3.0 -2.0
4  5.0  4.0 -1.0
5  3.0  2.0  1.0
6  1.0  3.0 -2.0
7  1.0  2.0  2.0
     a    b    c
0  2.0  1.0  2.0
1  1.0 -1.0  2.0
2  3.5  3.5  2.0
3  2.0  3.0  2.0
4  5.0  4.0 -1.0
5  3.0  2.0 -1.0
6  1.0  3.0 -2.0
7  1.0  2.0 -2.0
df.loc[df.index % 2 == 1, "c" ] = df.c * - 1