【问题标题】:Getting rid of lists of empty strings摆脱空字符串列表
【发布时间】:2020-06-24 16:00:53
【问题描述】:

我有一个包含空字符串列表的数据框:

df.Answers.head()
0    ['In next 3 months', 'In next 6 months', 'In n...
1    ["Doctor's availability in hotel", 'Ventilator...
2    ['Buffet breakfast with social distancing', 'B...
3    ['1', '2', '3', '4', '5', '6', '7', '8', '9', ...
4                                                 ['']

我想摆脱它们。所以我尝试了:

def remove_empty_arrays(answers):
...     if answers in [[''], ["'"], []]:
...         print("Got an empty bracket")
...         return None
... df.Answers.map(remove_empty_arrays)  

但它从来没有用过,我从来没有打印过任何确认匹配的消息。

更新

  • 我尝试了 Andrej Kesly 的答案,但它似乎打破了不为空的字符串:
    df.Answers.apply(lambda x: [v for v in x if v not in ('', '"')])
    0       [[, ', I, n,  , n, e, x, t,  , 3,  , m, o, n, ...
    1       [[, D, o, c, t, o, r, ', s,  , a, v, a, i, l, ...
    2       [[, ', B, u, f, f, e, t,  , b, r, e, a, k, f, ...
    3       [[, ', 1, ', ,,  , ', 2, ', ,,  , ', 3, ', ,, ...
    4                                            [[, ', ', ]]

  • 我也尝试了 Mahya Mk 的答案,但它摆脱了一切:
    def remove_empty_arrays(answers):
    ...     if answers in [["''"],['""']]:
    ...         print("Got an empty bracket")
    ...         return None
    ... df.Answers = df.Answers.map(remove_empty_arrays)    
    df.Answers.head()
    0    None
    1    None
    2    None
    3    None
    4    None
    Name: Answers, dtype: object

【问题讨论】:

    标签: arrays python-3.x list data-cleaning


    【解决方案1】:

    您可以使用列表推导来过滤列表项:

    例如:

    df = pd.DataFrame({'Answers':[ ['"', 'a', 'b', 'c'], ['d', 'e', ''], []]})
    
            Answers
    0  [", a, b, c]
    1      [d, e, ]
    2            []
    

    然后:

    df.Answers = df.Answers.apply(lambda x: [v for v in x if v not in ('', '"')])    
    print(df)
    

    打印:

         Answers
    0  [a, b, c]
    1     [d, e]
    2         []
    

    编辑:如果值只是字符串,不是字符串列表,你可以这样做:

    import requests
    from bs4 import BeautifulSoup
    from ast import literal_eval
    
    
    df = pd.DataFrame({'Answers':[ '''['"', 'a', 'b', 'c']''', '''['d', 'e', '']''', '''[]''']})
    
    df.Answers = df.Answers.apply(lambda x: [v for v in literal_eval(x) if v not in ('', '"')])
    print(df)
    

    打印:

         Answers
    0  [a, b, c]
    1     [d, e]
    2         []
    

    注意:最好从源头解决这个问题 - 所以不要将字符串放在数据框内,而是先解析它们(或者不要将它们保存为字符串而是字符串列表)。

    【讨论】:

    • 感谢您的回答!我试过了,但它似乎爆裂了不为空的字符串
    • @RevolucionforMonica 如果我查看您的编辑,这是否意味着['In next 3 months', 'In next 6 months', 'In n... 是一个字符串,而不是字符串列表?喜欢s = "['In next 3 months', 'In next 6 months']"
    • 你说得对。执行 df.Answers.head() 时我没有注意到,但是使用 df.Answers[0] 我确实有类似的东西
    【解决方案2】:

    我认为 Andrej 的回答是正确的。但你应该在你的列表中添加这个字符串: "''","""' 我怎样才能找到它? 我模拟了你的数据框,我看到你的空列表实际上并不是空的,因为你的输出。

    这是我的尝试: 首先,我创建一个这样的示例 DataFrame:

    data = {'Name': ['Tom', 'nick', 'krish', 'jack','mah','mahy','mahya','mahyam','mahyamk'], 'Age': [20, 21, 19, 18,20,21,23,23,24],'Answer':[ ['In next 3 months', 'In next 6 months', 'In month'],["Doctor's availability in hotel", 'Ventilator'],['1', '2', '3', '4', '5', '6', '7', '8', '9'],["''"],["''"],["''"],["''"],["''"],["''"]]}

    df = pd.DataFrame(data)
    
    df.Answer.head()
    

    我得到了这个输出:

    0    [In next 3 months, In next 6 months, In month]
    1      [Doctor's availability in hotel, Ventilator]
    2                       [1, 2, 3, 4, 5, 6, 7, 8, 9]
    3                                              ['']
    4                                              ['']
    5                                              ['']
    6                                              ['']
    7                                              ['']
    8                                              ['']
    Name: Answer, dtype: object>
    

    所以,我是这样评价它们的:

    for item in df.Answer:
        #print(item)
        if item in [["''"],['""']]:
          print("Got an empty bracket")
    

    【讨论】:

    • 感谢您的回答!不幸的是,它摆脱了一切:/我已经尝试更新了我的问题
    猜你喜欢
    • 2014-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 2010-10-12
    • 1970-01-01
    • 2020-07-24
    • 1970-01-01
    相关资源
    最近更新 更多