SLa*_*k A 3 dataframe python-3.x pandas
我知道以前也曾问过类似的问题,但我从字面上尝试了这里列出的所有可能的解决方案,但都没有用。
我有一个由日期,字符串,空值和空列表值组成的数据框。它非常大,有800万行。
我想替换所有空列表值-因此仅包含仅[]的单元格,而NaN则不包含其他任何单元格。似乎没有任何作用。
我尝试了这个:
df = df.apply(lambda y: np.nan if (type(y) == list and len(y) == 0) else y)
Run Code Online (Sandbox Code Playgroud)
正如在这个问题中类似建议的那样,在熊猫数据框中使用NaN替换空列表,但它不会更改我的数据框中的任何内容。
任何帮助,将不胜感激。
只是假设OP想要将空列表,字符串'[]'和对象'[]'转换为na,下面是一个解决方案。
设定
#borrowed from piRSquared's answer.
df = pd.DataFrame([
[1, 'hello', np.nan, None, 3.14],
['2017-06-30', 2, 'a', 'b', []],
[pd.to_datetime('2016-08-14'), 'x', '[]', 'z', 'w']
])
df
Out[1062]:
0 1 2 3 4
0 1 hello NaN None 3.14
1 2017-06-30 2 a b []
2 2016-08-14 00:00:00 x [] z w
Run Code Online (Sandbox Code Playgroud)
解:
#convert all elements to string first, and then compare with '[]'. Finally use mask function to mark '[]' as na
df.mask(df.applymap(str).eq('[]'))
Out[1063]:
0 1 2 3 4
0 1 hello NaN None 3.14
1 2017-06-30 2 a b NaN
2 2016-08-14 00:00:00 x NaN z w
Run Code Online (Sandbox Code Playgroud)