[英]Alternative values in a column to test with .isin() pandas (python)
考虑两个数据帧:
df1 = pd.DataFrame(['apple and banana are sweet fruits','how fresh is the banana','cherry from japan'],columns=['fruits_names'])
df2 = pd.DataFrame([['apple','red'],['banana','yellow'],['cherry','black']],columns=['fruits','colors'])
然后代码:
colors =[]
for f in df1.fruits_names.str.split().apply(set): #convert content in a set with splitted words
color = [df2[df2['fruits'].isin(f)]['colors']] #matching fruits in a list
colors.append(color)
我可以轻松地在 df1 中插入颜色
df1['color'] = colors
output:
fruits_names color
0 apple and banana are sweet fruits [[red, yellow]]
1 how fresh is the banana [[yellow]]
2 cherry from japan [[black]]
问题是“水果”列是否具有替代值,例如:
df2 = pd.DataFrame([[['green apple|opal apple'],'red'],[['banana|cavendish banana'],'yellow'],['cherry','black']],columns=['fruits','colors'])
如何保持此代码正常工作?
我最后尝试的是创建一个带有水果分隔值的新列:
df2['Types'] = cf['fruits'].str.split('|')
和 .apply(tuple) 在这里:
color = [df[df['Types'].apply(tuple).isin(f)]['colors']]
但它不匹配。
我认为你需要:
print(df1)
fruits_names
0 green apple and banana are sweet fruits
1 how fresh is the banana
2 cherry and opal apple from japan
使用split
和df.explode()
df2["fruits"] = df2["fruits"].apply(lambda x: x.split("|"))
df2 = df2.explode("fruits")
print(df2)
输出:
fruits colors
0 green apple red
0 opal apple red
1 banana yellow
1 cavendish banana yellow
2 cherry black
将其转换为dict
d = {i:j for i,j in zip(df2["fruits"].values, df2["colors"].values)}
根据条件创建列
df1["colors"] = [[v for k,v in d.items() if k in x] for x in df1["fruits_names"]]
print(df1)
最终输出:
fruits_names colors
0 green apple and banana are sweet fruits [red, yellow]
1 how fresh is the banana [yellow]
2 cherry and opal apple from japan [red, black]
import pandas as pd
import numpy as np
df1 = pd.DataFrame(['green apple and banana are sweet fruits','how fresh is the banana','cherry from japan'],columns=['fruits_names'])
df2 = pd.DataFrame([['green apple|opal apple','red'],['banana|cavendish banana','yellow'],['cherry','black']],columns=['fruits','colors'])
df2['sep_colors'] = np.where(df2['fruits'], (df2['fruits'].str.split(pat='|')), df2['fruits'])
dic = dict(zip(df2['colors'].tolist(),df2['sep_colors'].tolist()))
final = []
for row in range(len(df1.fruits_names)):
list1 = []
for key, value in dic.items():
for item in value:
if item in df1.iloc[row][0]:
list1.append(key)
final.append(list1)
df1['colors'] = final
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.