【问题标题】:Read each string in a row_python读取 row_python 中的每个字符串
【发布时间】:2021-08-08 17:28:09
【问题描述】:

我有一个 df,其中列“元素”如下所示:

如何将每个单词用作分隔符“|”然后将每个单词作为避免重复的键发送? 我用过这个,但它不起作用:

    for row in df.elements.itertuples():
       for l in row.elements.split("|"):
           list_elem.send_keys(l)

【问题讨论】:

  • Please don't use images for data。将屏幕上的文本复制并粘贴到问题中似乎比截屏文本更容易。
  • @MDR 我确实复制和粘贴但显示为图像,我没有使用截图。
  • 无论如何它仍然显示为图像,所以你不应该只是耸耸肩离开它。再次从源代码复制,粘贴到基本文本编辑器中,复制然后粘贴到问题中。此外,通过阅读您对建议答案的评论,您需要详细解释“将每个单词作为键发送”的含义(如果您正在谈论 Selenium 的 send_keys() 方法,可能并不明显)。如果你想要一个好的答案,你必须努力解释这个问题。
  • @MDR 谢谢,在粘贴之前使用基本的文本编辑器实际上是一个很好的解决方案,从现在开始会这样做。是的,我指的是 selenium 的 send_keys() 方法,会更新问题。
  • 你可以使用这个文本:{'elements': {0: 'Plastica | plastica | plastic', 1: 'Metallo | metallo', 2: 'Acciaio inossidabile | acciaio inossidabile | acciaio | albero della gomma'}}

标签: python pandas split


【解决方案1】:

试试这个:

import pandas as pd
df = pd.DataFrame({'elements': ['Plastica|plastic|plastica', 'Metallo|metallo']})
df2 = df['elements'].str.split("|", expand=True)
df2 = df2.stack().reset_index().rename(columns={0: 'elements'})
df2['elements'] = df2['elements'].str.lower()
df2 = df2.drop_duplicates(subset=['elements'])
df2

【讨论】:

  • 谢谢,问题是,例如,如果我将 Plastica 作为密钥发送,下一步是将 Plastica 作为密钥发送到另一个 webelement,然后我发送塑料,我需要再次发送 Plastica 等等在。基本上,对于在第一个单词之后找到的每个关键字,我每次都会发送第一个单词。
  • 不确定你的意思。请举个例子
【解决方案2】:

根据需要修改:

#for each row in the frame
for index, row in df.iterrows():
    #if blank skip it
    if row['elements'] == '':
        continue
    #if '|' isn't in the string skip it too
    elif '|' not in row['elements']:
        continue
    else:
        #split the string into a list by the the '|' char
        l = row['elements'].split('|')
        #remove whitespace from the beginning and end of each item
        l = [x.strip() for x in l]
        #for each item in the list
        for i, item in enumerate(l):
            #if the first item
            if i == 0:
                #send; print for testing
                print(item)
            #if not the first item
            else:
                #send; print (for testing) first and current item; 
                #break this into two lines if required
                print(l[0], item)

输出:

Plastica
Plastica plastica
Plastica plastic
Metallo
Metallo metallo
Acciaio inossidabile
Acciaio inossidabile acciaio inossidabile
Acciaio inossidabile acciaio
Acciaio inossidabile albero della gomma

【讨论】:

    猜你喜欢
    • 2020-09-08
    • 2017-09-27
    • 2012-11-12
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    • 2013-10-04
    • 2013-05-17
    相关资源
    最近更新 更多