假設我有一個如下所示的 csv+-----+-----------+---------+| ID | state | city |+-----+-----------+---------+| 101 | READY | || 101 | DELIVERED | NEWYORK || 101 | DELIVERED | LONDON | | 102 | READY | || 102 | DELIVERED | LONDON || 103 | READY | || 103 | DELIVERED | NEWYORK || 104 | READY | || 104 | DELIVERED | TOKYO || 104 | DELIVERED | PARIS || 105 | DELIVERED | NEWYORK |+-----+-----------+---------+現在我想要帶有 State 的 ID,READY它有DELIVEREDas NEWYORK。相同的 ID 會在不同的州和城市出現多次??偸荝EADYcity為空cityDELIVERED總是有一些值。city所以首先我想檢查DELIVERED列的值state。如果是 NEWYORK,則取該 ID 的 READY 行。如果沒有對應READY的行,那么我們可以忽略(本例中的 ID 105)預期產出+-----+-----------+---------+| ID | state | city |+-----+-----------+---------+| 101 | READY | || 103 | READY | |+-----+-----------+---------+我試過在熊貓中使用自我加入。但是我不知道如何繼續,因為我是 python 的新手。目前我正在用 SQL 做這件事。import pandas as pdmydata = pd.read_csv('C:/Mypython/Newyork',encoding = "ISO-8859-1")NY = pd.merge(mydata,mydata,left_on='ID',right_on='ID',how='inner')
2 回答

拉風的咖菲貓
TA貢獻1995條經驗 獲得超2個贊
讓我們嘗試用布爾索引來groupby().transform()識別那些:NEWYORK
has_NY = df['city'].eq('NEWYORK').groupby(df['ID']).transform('any')
mask = df['state'].eq('READY') & has_NY
df[mask]
輸出:
ID state city
0 101 READY None
5 103 READY None

慕工程0101907
TA貢獻1887條經驗 獲得超5個贊
使用NEWYORK條件獲取 ID 列表,然后使用該列表進行過濾。
new_york_ids = df.loc[df['city']=='NEWYORK', 'ID']
df[(df['state']=='READY') & (df['ID'].isin(new_york_ids))]
ID state city
0 101 READY None
5 103 READY None
添加回答
舉報
0/150
提交
取消