python - 查找具有不同标题的行

标签 python pandas dataframe

我的数据框

    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/

相关文章:

python - 摆脱 Pandas 中的分层索引

python - Pandas :如何将具有多个值的单元格转换为多行?

Python解析数据框元素

python - 选择周期边界之间的行并将它们放入数组 | python | Pandas 数据框

Python - 组合类的继承

python - MYSQL select 只选择字符而不选择名称

python - __name__ 属性的其他用途

python - Pandas 创建引用自身的列

r - 将函数应用于 R 中数据框中每一行的特定列

python - 无法安装模块 PIL - 错误 - 找不到满足 PI 要求的版本