更改特定行熊猫的标志

时间:2018-01-19 11:20:20

标签: python pandas

这是我的第一篇文章,所以我试图以正确的格式进行。我有两列文本和值和索引日期。

Date  Zweck  Betrag                                 
2014-09-26 00:00:00   Gehalt    22.0  
2014-09-26 01:00:00     REWE     1.0  
2014-09-26 02:00:00    Edeka    76.0  
2014-09-26 03:00:00     Bike    51.0  
2014-09-26 04:00:00      ING    64.0  
2014-09-26 05:00:00  Allianz    93.0  
2014-09-26 06:00:00     Bahn     8.0  
2014-09-26 07:00:00  Kaufhof    33.0  
2014-09-26 08:00:00       CA     6.0  
2014-09-26 09:00:00    Shell    55.0  

我想做的是如果Text不是Salary,则翻转每行中的符号(所以为负值)。我用这种方法尝试过,但我不行:

for r in np.arange(len(df)):
            if df.ix[r].Zweck != 'Gehalt':
                    betrag = df.ix[r].Betrag
                    df.loc[r, 'Betrag'] = -1 * betrag 

1 个答案:

答案 0 :(得分:4)

选项1
你不必循环迭代。熊猫' loc为您提供此替代品。

df.loc[df.Zweck != 'Gehalt', 'Betrag'] *= -1

df

                  Date    Zweck  Betrag
0  2014-09-26 00:00:00   Gehalt    22.0
1  2014-09-26 01:00:00     REWE    -1.0
2  2014-09-26 02:00:00    Edeka   -76.0
3  2014-09-26 03:00:00     Bike   -51.0
4  2014-09-26 04:00:00      ING   -64.0
5  2014-09-26 05:00:00  Allianz   -93.0
6  2014-09-26 06:00:00     Bahn    -8.0
7  2014-09-26 07:00:00  Kaufhof   -33.0
8  2014-09-26 08:00:00       CA    -6.0
9  2014-09-26 09:00:00    Shell   -55.0

这项任务是在适当的,便宜的,快速的。

选项2
或者,您可以使用np.where,它会为您提供一个可以分配的新系列。

df['Betrag'] = np.where(df.Zweck != 'Gehalt', df.Betrag * -1, df.Betrag)

df

                  Date    Zweck  Betrag
0  2014-09-26 00:00:00   Gehalt    22.0
1  2014-09-26 01:00:00     REWE    -1.0
2  2014-09-26 02:00:00    Edeka   -76.0
3  2014-09-26 03:00:00     Bike   -51.0
4  2014-09-26 04:00:00      ING   -64.0
5  2014-09-26 05:00:00  Allianz   -93.0
6  2014-09-26 06:00:00     Bahn    -8.0
7  2014-09-26 07:00:00  Kaufhof   -33.0
8  2014-09-26 08:00:00       CA    -6.0
9  2014-09-26 09:00:00    Shell   -55.0

选项3 另一个,mask / where -

df.Betrag = df.Betrag.where(df.Zweck != 'Gehalt', df.Betrag)

或者,

df.Betrag = df.Betrag.mask(df.Zweck == 'Gehalt', df.Betrag)

或者,您可以使用df.update代替,这样就无需再分配。

df.update(df.Betrag.where(df.Zweck != 'Gehalt', df.Betrag))

df

                  Date    Zweck  Betrag
0  2014-09-26 00:00:00   Gehalt    22.0
1  2014-09-26 01:00:00     REWE    -1.0
2  2014-09-26 02:00:00    Edeka   -76.0
3  2014-09-26 03:00:00     Bike   -51.0
4  2014-09-26 04:00:00      ING   -64.0
5  2014-09-26 05:00:00  Allianz   -93.0
6  2014-09-26 06:00:00     Bahn    -8.0
7  2014-09-26 07:00:00  Kaufhof   -33.0
8  2014-09-26 08:00:00       CA    -6.0
9  2014-09-26 09:00:00    Shell   -55.0