Python 更改特定行中的符号

Python 更改特定行中的符号,python,pandas,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

这是我的第一篇文章,所以我正试图用正确的格式来写。我有两列,分别是文本、值和索引日期

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  
如果文本不是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
您不必使用循环进行迭代。Pandas的
loc
为您将此替换矢量化

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

作业到位,便宜,快捷


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

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


选项3 另一个,带有
掩码
/
其中
-

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

或者,您可以改用
df.update
,这样就无需重新分配

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


df.loc[df.Zweck!='Gehalt','Betrag']*=-1
非常感谢您的支持。真棒的回答@皮因斯基:我通常不得不这么说,但这次是你替我说的。谢谢!:-)接受答案只是提高投票率,或者我应该在哪里做呢?你还没有提高投票率的声誉分数。但是你可以接受你的问题的答案。每个答案投票计数器下方都有一个可见的勾号。也会增加你自己的声誉分数。
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