让我们以这个小数据框为例:
df = pd.DataFrame(dict(Name=['abc','abcd','bc']))
Name
0 abc
1 abcd
2 bc
我想创建一个新的数据框:
- 使其索引和列名称等于列名称的值
- 如果索引属于列名,则其值等于 true 或 false
预期输出:
abc abcd bc
abc True True False
abcd False True False
bc True True True
请问我该怎么办?
最佳答案
使用Series.str.contains
在列表理解中,创建掩码并通过 concat
连接在一起,然后设置索引,转置为DataFrame.T
最后通过 DataFrame.rename_axis
删除索引和列名称:
s = df['Name']
L = [s.str.contains(x) for x in s]
df = pd.concat(L, axis=1, keys=s).set_index(s).T.rename_axis(index=None, columns=None)
print (df)
abc abcd bc
abc True True False
abcd False True False
bc True True True
关于python - 如何让字符串列的所有包含匹配项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61631826/