簡體   English   中英

在Python中循環:根據其他列中的值修改一列

[英]Looping in Python: modify one column based on values in other columns

當前數據:

存儲為Pandas DataFrame

print(df)

col1 | col2 
A    | 1
B    | 3
C    | 3
D    | 7
E    | 4
C    | 3

目標:

我想創建一個新列,如果col1是A,C或E,則向col2加1。

col1 | col2  | col2_corrected
A    | 1     | 2
B    | 3     | 3
C    | 3     | 4
D    | 7     | 7
E    | 4     | 5
C    | 3     | 4

我失敗的解決方案:

add_one_to_me = ['A','C','E']

if df.col1.isin(add_one_to_me):
    df.col2_corrected = df.col2 + 1
else: df.col2_corrected = df.col2

由於正在評估整個系列的真相,因此引發了關於歧義真相的錯誤。

如何將其應用於DataFrame的每一行? 我是Python和編程的新手,所以這是一個非常基本的問題。

提前致謝!

# Copy the existing column over
df['col2_corrected'] = df.col2

# Increment the values of only those items where col1 is A C or E
df.loc[df.col1.isin(['A', 'C', 'E']), 'col2_corrected'] += 1

df
Out[]: 
  col1  col2  col2_corrected
0    A     1               2
1    B     3               3
2    C     3               4
3    D     7               7
4    E     4               5
5    C     3               4

您收到該錯誤的原因是從if df.col1.isin(add_one_to_me):

如果我們看一下: df.col1.isin(add_one_to_me)

Out[]: 
0     True
1    False
2     True
3    False
4     True
5     True

而且這與if語句無關。 您可以做的是迭代檢查col1每個項目,然后將col2_corrected遞增1。 這可以通過使用df.apply(...)for index, row in df.iterrows():來完成for index, row in df.iterrows():

您可以使用以下事實: True的整數值為1

df['col2_corrected'] = df['col2'] + df['col1'].isin(add_one_to_me)

您也可以使用map功能,即

df['new'] = df['col1'].map({'A':1,'C':1,'E':1}).fillna(0) + df['col2']

   col1  col2  new
0    A     1  2.0
1    B     3  3.0
2    C     3  4.0
3    D     7  7.0
4    E     4  5.0
5    C     3  4.0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM