gpt4 book ai didi

python - 更改特定行 Pandas 的标志

转载 作者:行者123 更新时间:2023-11-28 22:21:25 27 4
gpt4 key购买 nike

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

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
您不必使用循环进行迭代。 Pandas 的 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

关于python - 更改特定行 Pandas 的标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48339956/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com