我的数据框
Name Value
0 K <apple WK1>
contents
1 Y <banana WK2>
contents
2 B <orange WK1>
contents
3 Q <grape WK31>
contents
4 C <apple WK12>
contents
5 A <apple WK22>
contents
如您所见,“值”列的第一行有标题。下面是其他内容。
我想要删除重复值的这些标题。
如果你注意标题,其他字符如WK
混合在一起,但将其删除
我想要得到以下结果。
Title
0 <apple>
1 <banana>
2 <orange>
3 <grape>
现有数据框不维护也没关系。
但是,我只想获取不重叠的标题值。
重现:
df1 = df(data={'Name' : ['K', 'Y', 'B','Q','C','A'], 'Value' : ['<apple WK1>','<banana WK2>','<orange WK1>','<grape WK31>','<apple WK12>','<apple WK22>']}, columns = ['Name', 'Value'])
最佳答案
尝试 extract
和 drop_duplicates
:
df["Value"].str.extract(r'<([a-z]*)\s+').drop_duplicates()
如果你想保留<
和>
:
(df["Value"].str.extract(r'(<[a-z]*)\s+') + ">").drop_duplicates()
完整示例:
# build dataframe
df = pd.DataFrame(data={'Name' : ['K', 'Y', 'B','Q','C','A'], 'Value' : ['<apple WK1>','<banana WK2>','<orange WK1>','<grape WK31>','<apple WK12>','<apple WK22>']}, columns = ['Name', 'Value'])
print(df)
# Name Value
# 0 K <apple WK1>
# 1 Y <banana WK2>
# 2 B <orange WK1>
# 3 Q <grape WK31>
# 4 C <apple WK12>
# 5 A <apple WK22>
# Only select content
out_1 = df["Value"].str.extract(r'<([a-z]*)\s+').drop_duplicates()
print(out_1)
# 0
# 0 apple
# 1 banana
# 2 orange
# 3 grape
# Select content and "<" - ">"
out_2 = (df["Value"].str.extract(r'(<[a-z]*)\s+') + ">").drop_duplicates()
print(out_2)
# 0
# 0 <apple>
# 1 <banana>
# 2 <orange>
# 3 <grape>
关于python - 查找具有不同标题的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60814007/