在存在相似之处的Pandas系列中插入多个元素 [英] Insert multiple elements into Pandas Series where similarities exist

查看:88
本文介绍了在存在相似之处的Pandas系列中插入多个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里,我想在标签中有两行带有"href"的行之间插入行"<td class='test'>None</td>" -请注意,带有href的每一行都不相同.

Here I'd like to insert the row "<td class='test'>None</td>" between wherever there are two rows with "href" in the tag--note, each row with href is NOT identical.

import pandas as pd

table = pd.Series(

        ["<td class='test'><a class='test' href=...", # 0 
        "<td class='test'>A</td>",                    # 1
        "<td class='test'><a class='test' href=...",  # 2
        "<td class='test'>B</td>",                    # 3
        "<td class='test'><a class='test' href=...",  # 4
        "<td class='test'><a class='test' href=...",  # 5
        "<td class='test'>C</td>",                    # 6
        "<td class='test'><a class='test' href=...",  # 7 
        "<td class='test'>F</td>",                    # 8
        "<td class='test'><a class='test' href=...",  # 9 
        "<td class='test'><a class='test' href=...",  # 10 
        "<td class='test'>X</td>"])                   # 11

insertAt = []
for i in range(0, len(table)):
  if 'href' in table[i] and 'href' in table[i+1]:
    print(i + 1, ' is duplicated')
    insertAt.append(i)

# 5  is duplicated
# 10  is duplicated
# [4, 9]

这是输出的外观:

#         ["<td class='test'><a class='test' href=...", # 0 
#         "<td class='test'>A</td>",                    # 1
#         "<td class='test'><a class='test' href=...",  # 2
#         "<td class='test'>B</td>",                    # 3
#         "<td class='test'><a class='test' href=...",  # 4
#         "<td class='test'>None</td>",                 # 5 Insert "<td class='test'>None</td>"
#         "<td class='test'><a class='test' href=...",  # 6
#         "<td class='test'>C</td>",                    # 7
#         "<td class='test'><a class='test' href=...",  # 8 
#         "<td class='test'>F</td>",                    # 9
#         "<td class='test'><a class='test' href=...",  # 10
#         "<td class='test'>None</td>",                 # 11 Insert <td class='test'>None</td>"
#         "<td class='test'><a class='test' href=...",  # 12 
#         "<td class='test'>X</td>"]                    # 13

推荐答案

如果您使用numpy,可以轻松实现.

Than can be easily achieved if you go to numpy.

在您的示例中:

dups = table.str.contains('href') & table.shift(1).str.contains('href')

array = np.insert(table.values, dups[dups].index, "<td class='test'>None</td>")

pd.Series(array)

这篇关于在存在相似之处的Pandas系列中插入多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆