您好我想从我的数据框中选择某些数据,如下所示。不知怎的,我的If语句不能正常工作并选择,例如而不是6M和6M3M的所有可能性意味着6M,3M和6M3M。我想玩if语句。代码如下所示:
import pandas as pd
df = pd.DataFrame([
['Alex', 'Germany', '6M', 28, 'Surfer'],
['Paul', 'Germany', '6M', 25, 'Surfer'],
['Carly', 'Germany', '6M', 22, 'Surfer'],
['Richard', 'Germany', '6M', 20, 'Surfer'],
['Lee', 'UK', '6M3M', 22, 'Kite'],
['Bob', 'UK', '6M3M', 23, 'Kite'],
['Judith', 'UK', '6M3M', 29, 'Kite'],
['Stephan', 'Spain', '3M', 29, 'Basketball'],
['Wendy', 'Spain', '3M', 23, 'Basketball'],
['Dennis', 'Spain', '3M', 25, 'Basketball'],
['Tucker', 'Germany', '3M', 22, 'Basketball'],
['Paula', 'Germany', '3M', 21, 'Basketball'],
], columns=['Name', 'Country', 'Course', 'Age', 'Sport'])
for index, row in df.iterrows():
if (row['Country'] == 'Germany') or (row['Country'] == 'UK') or (row['Course'] == '6M') or (row['Course'] == '6M3M'):
print(row['Name'], row['Country'], row['Age'], row['Sport'], row['Course'])
我的输出如下:
Alex Germany 28 Surfer 6M
Paul Germany 25 Surfer 6M
Carly Germany 22 Surfer 6M
Richard Germany 20 Surfer 6M
Lee UK 22 Kite 6M3M
Bob UK 23 Kite 6M3M
Judith UK 29 Kite 6M3M
Tucker Germany 22 Basketball 3M
Paula Germany 21 Basketball 3M
但我只想:
Alex Germany 28 Surfer 6M
Paul Germany 25 Surfer 6M
Carly Germany 22 Surfer 6M
Richard Germany 20 Surfer 6M
Lee UK 22 Kite 6M3M
Bob UK 23 Kite 6M3M
Judith UK 29 Kite 6M3M
答案 0 :(得分:2)
您的if
逻辑不正确。它应该是:
if row['Country'] in {'Germany', 'UK'} and row['Course'] in {'6M', '6M3M'}:
print(row['Name'], row['Country'], row['Age'], row['Sport'], row['Course'])
有关在in
声明中使用if
的说明,请查看this answer。