How to add a column through the key of the pandas column content matching dictionary
Editor to share with you how to add a column through the key of the pandas column content matching dictionary, I believe most people do not know much about it, so share this article for your reference. I hope you will learn a lot after reading this article. Let's learn about it together.
This is a question of Zhihu. The original question is as follows:
I want to generate the Q column type based on the keywords of the counterparty in the H column. For example, the first column H contains "beautiful", then the Q column is "electrical appliances".
If I will add one by one, I want to generate a dictionary {"official": "electrical appliances", "network technology": "investment". }, add a column to match the type by matching the H column contents of the dataframe containing the dictionary key. Could you tell me how to operate?
Let me answer this question:
The general idea is to use the key value of traversing the dictionary, then use in to determine, and return value''' if true
# constructed dictionary
> my_dict = {'bo':' Aids, 'jik':' bones, 'luc':' C'}
# constructed dataframe
> df = pd.read_excel (ringing DVOGRAPHY myExcel) 1.xlsx')
> df
Name score
0 bob 45
1 jiken 67
2 bob 23
3 bob 34
4 lucy 42
5 lucy 75
# define function, make logical judgment > def get_res (strings): for key, value in my_dict.items (): if key in strings: return value return "" # apply the apply function to each line of name to get the returned result and return the grade column
> df ['grade'] = df [' name'] .apply (lambda x: get_res (x))
> df
Name score grade
0 bob 45 A
1 jiken 67 B
2 bob 23 A
3 bob 34 A
4 lucy 42 C
5 lucy 75 C above is "how to add a column through the key of the pandas column content matching Dictionary". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!