[英]new column in pandas DataFrame based on unique values (lists) of an existing column
[英]Python Pandas Dataframe: add new column based on existing column, which contains lists of lists
我正在尝试在下面的 dataframe 中添加一列,这将告诉我一个人是否属于绿色类别。 对于那个人,它只会显示 Y 或 N,具体取决于列类别是否包含它。 问题是列类别在某些行中仅包含一个字符串,而在其他行中包含字符串列表,甚至在其他行中包含列表列表。
import pandas as pd
df = pd.DataFrame({'user': ['Bob', 'Jane','Theresa', 'Alice'],
'category': [[['green'],['red']],'blue',['green'],[['yellow','purple'],'green','brown']]})
我怎样才能看到每一行的列是否包含特定的“绿色”字符串?
谢谢你。
我不会费心展平列表,只需使用基本的字符串匹配:
df['category'].astype(str).str.contains(r'\bgreen\b')
0 True
1 False
2 True
3 True
Name: category, dtype: bool
添加单词边界检查\b
这样我们就不会意外匹配诸如“greenery”或“greenwich”之类的单词,它们将“green”作为较大单词的一部分。
df.assign(has_green=df['category'].astype(str)
.str.contains(r'\bgreen\b')
.map({True: 'Y', False: 'N'}))
user category has_green
0 Bob [[green], [red]] Y
1 Jane blue N
2 Theresa [green] Y
3 Alice [[yellow, purple], green, brown] Y
您需要使用递归 flatten 。
import pandas as pd
df = pd.DataFrame({'user': ['Bob', 'Jane','Theresa', 'Alice'], 'category': [[['green'],['red']],'blue',['green'],[['yellow','purple'],'green','brown']]})
def flatten(x):
rt = []
for i in x:
if isinstance(i,list): rt.extend(flatten(i))
else: rt.append(i)
return rt
def is_green(x):
flat_list = flatten(x)
if "green" in flat_list:
return True
else:
return False
df["has_green"] = df["category"].apply(lambda x: is_green(x))
print(df)
user category has_green
0 Bob [[green], [red]] True
1 Jane blue False
2 Theresa [green] True
3 Alice [[yellow, purple], green, brown] True
尽管我同意基本字符串匹配可以解决问题的目的,但我想提请注意一个事实,即使用pd.core.common.flatten
可以很容易地实现扁平化列表:
import pandas as pd
import ast
df = pd.DataFrame({'user': ['Bob', 'Jane','Theresa', 'Alice', 'John'],
'category': [[['green'],['red']],'blue',['green'],[['yellow','purple'],'green','brown'], None]})
def fix_list(text):
try:
if '[' in text:
text = ast.literal_eval(text)
else:
text = [text]
except:
text = []
return list(pd.core.common.flatten(text))
df['category'] = df['category'].apply(fix_list)
df['green'] = df['category'].apply(lambda x: 'green' in x)
结果:
用户 | 类别 | 绿色 | |
---|---|---|---|
0 | 鲍勃 | ['绿色','红色'] | 真的 |
1 | 简 | ['蓝色的'] | 错误的 |
2 | 有个 | ['绿色'] | 真的 |
3 | 爱丽丝 | ['黄色','紫色','绿色','棕色'] | 真的 |
4 | 约翰 | [] | 错误的 |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.