【发布时间】: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