我有一个名为sample.csv的csv文件:
CODE HOME_TEAM AWAY_TEAM
0001 Lakers Jazz
0002 Raptors Lakers
0003 Warriors Portland
0004 Mavericks Lakers
0005 Celtics Mavericks
我希望根据用户输入打印团队参与的每一场比赛。假设在上面的例子中;湖人队;程序应该打印:
CODE HOME_TEAM AWAY_TEAM
0001 Lakers Jazz
0002 Raptors Lakers
0004 Mavericks Lakers
到目前为止,我编码的内容(见下文(分别打印信息。
import pandas as pd
df = pd.read_csv("sample.csv")
select_Team = input("Which team do you like to see: ")
df2 = df[df["HOME_TEAM"] == select_Team]
df3 = df[df["AWAY_TEAM"] == select_Team]
print(df2)
print(df3)
我应该怎么做才能将信息作为一个整体呈现(就像我上面展示的那样(?
如果您想同时包含两个条件
df2 = df[(df["HOME_TEAM"] == select_Team) | (df["AWAY_TEAM"] == select_Team)]
让我们尝试eq
和any
PS是团队不止一次将eq
更改为isin
out = df[df.eq('Lakers').any(1)] # df[df.isin(['Lakers']).any(1)]
Out[462]:
CODE HOME_TEAM AWAY_TEAM
0 1 Lakers Jazz
1 2 Raptors Lakers
3 4 Mavericks Lakers
如果输入的团队不在DataFrame:中,您也可以创建一些逻辑来引发值错误
select_Team = input("Which team do you like to see: ")
df2 = df[(df['HOME_TEAM'].str.lower() == select_Team.lower()) | (df['AWAY_TEAM'].str.lower() == select_Team.lower())]
if len(df2) == 0:
raise ValueError(f"{select_Team} is not in the DataFrame. The teams available are {set(df[['HOME_TEAM', 'AWAY_TEAM']].stack())}")
else:
print(df2)