使用 pandas 根据其他行过滤掉行

A.N*_*.N. 3 python numpy pandas

我有一个如下所示的数据框:

dict = {'companyId': {0: 198236, 1: 198236, 2: 900814, 3: 153421, 4: 153421, 5: 337815},
 'region': {0: 'Europe', 1: 'Europe', 2: 'Asia-Pacific', 3: 'North America', 4: 'North America', 5:'Africa'},
 'value': {0: 560, 1: 771, 2: 964, 3: 217, 4: 433, 5: 680},
 'type': {0: 'actual', 1: 'forecast', 2: 'actual', 3: 'forecast', 4: 'actual', 5: 'forecast'}}

df = pd.DataFrame(dict)

    companyId     region          value  type
0   198236        Europe          560    actual
1   198236        Europe          771    forecast
2   900814        Asia-Pacific    964    actual
3   153421        North America   217    forecast
4   153421        North America   433    actual
5   337815        Africa          680    forecast
Run Code Online (Sandbox Code Playgroud)

我似乎无法找到一种根据以下条件过滤掉某些行的方法:

如果在同一个条目下有两个条目,就像andcompanyId的情况一样,我只想保留is 的条目。198236153421typeactual

如果 a 下只有一个条目(就像和 的companyId情况一样),我想保留该行,而不管 column 中的值如何。337815900814type

有谁知道如何解决这个问题?

WeN*_*Ben 8

你可以检查argsort一下drop_duplicates

out = df.iloc[df.type.ne('actual').argsort()].drop_duplicates('companyId')
Out[925]: 
   companyId         region  value      type
0     198236         Europe    560    actual
2     900814   Asia-Pacific    964    actual
4     153421  North America    433    actual
5     337815         Africa    680  forecast
Run Code Online (Sandbox Code Playgroud)