0
Follow
0
View

Passing a list and lookup first (non empty) match in Pandas data frame

dd5323400 注册会员
2023-01-25 16:52

You can dropna, drop_duplicates, convert to Series and then to_dict:

lst = ['a','b','c']

my_dict = (df.dropna(subset=['B'])
             .drop_duplicates(subset=['A'])
             .set_index('A')
             .loc[lst, 'B'].to_dict()
           )

Alternative:

my_dict = df.dropna(subset='B').groupby('A')['B'].first().to_dict()

output: {'a': 'he', 'b': 'I', 'c': 'them'}

About the Author

Question Info

Publish Time
2023-01-25 16:52
Update Time
2023-01-25 16:52