[英]create new column using a dictionary key
拿这个 dataframe df
:
df = pd.DataFrame({'col_1':['some text green', 'some text blue', 'some text dog', 'some text']})
col_1
0 some text green
1 some text blue
2 some text dog
3 some text
拿这本字典:
my_dict = {'color':['green', 'blue'],'animal':['dog']}
如果字符串包含在col_1
中,我需要创建一个新列new_col
搜索。 字符串在字典值中给出。 如果是这样,我需要获取字典键并将其放在新列中。 如果没有,只需放置 NaN。
结果应该是:
col_1 new_col
0 some text green color
1 some text blue color
2 some text dog animal
3 some text NaN
尝试这个:
def f(s):
for k in my_dict:
for v in my_dict[k]:
if v in s:
return k
df["new_col"] = df["col_1"].apply(f)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.