jlt*_*199 15 python dataframe pandas
我有一个大型数据帧.当它被创建时,'None'被用作无法计算数字的值(而不是'nan')
如何删除任何列中包含"无"的所有行?我虽然可以使用df.dropna并设置值na,但我似乎无法做到.
谢谢
我认为这是数据帧的一个很好的代表:
temp = pd.DataFrame(data=[['str1','str2',2,3,5,6,76,8],['str3','str4',2,3,'None',6,76,8]])
Run Code Online (Sandbox Code Playgroud)
piR*_*red 18
设置
Borrowed @ MaxU'sdf
df = pd.DataFrame([
[1, 2, 3],
[4, None, 6],
[None, 7, 8],
[9, 10, 11]
], dtype=object)
Run Code Online (Sandbox Code Playgroud)
解决方案
您可以pd.DataFrame.dropna按原样使用
df.dropna()
0 1 2
0 1 2 3
3 9 10 11
Run Code Online (Sandbox Code Playgroud)
假设你有None像这样的字符串df
df = pd.DataFrame([
[1, 2, 3],
[4, 'None', 6],
['None', 7, 8],
[9, 10, 11]
], dtype=object)
Run Code Online (Sandbox Code Playgroud)
然后结合dropna使用mask
df.mask(df.eq('None')).dropna()
0 1 2
0 1 2 3
3 9 10 11
Run Code Online (Sandbox Code Playgroud)
您可以确保object在比较时使用整个数据帧.
df.mask(df.astype(object).eq('None')).dropna()
0 1 2
0 1 2 3
3 9 10 11
Run Code Online (Sandbox Code Playgroud)
jlt*_*199 11
感谢你的帮助.最后我得到了
df = df.replace(to_replace='None', value=np.nan).dropna()
上班.我不确定为什么你的建议不适合我.
更新:
In [70]: temp[temp.astype(str).ne('None').all(1)]
Out[70]:
0 1 2 3 4 5 6 7
0 str1 str2 2 3 5 6 76 8
Run Code Online (Sandbox Code Playgroud)
老答案:
In [35]: x
Out[35]:
a b c
0 1 2 3
1 4 None 6
2 None 7 8
3 9 10 11
In [36]: x = x[~x.astype(str).eq('None').any(1)]
In [37]: x
Out[37]:
a b c
0 1 2 3
3 9 10 11
Run Code Online (Sandbox Code Playgroud)
In [47]: x = x[x.astype(str).ne('None').all(1)]
In [48]: x
Out[48]:
a b c
0 1 2 3
3 9 10 11
Run Code Online (Sandbox Code Playgroud)