TJa*_*ain 2 python dataframe pandas
我有一个熊猫数据框,我试图根据具有完全相同值的所有列删除行。这是一个帮助理解这个想法的例子。
输入:
index A B C D E F ....
0 1 2 3 1 3 4
1 2 2 2 2 2 2
2 5 5 5 5 5 5
3 7 7 6 7 7 7
Run Code Online (Sandbox Code Playgroud)
输出:
index A B C D E F ....
0 1 2 3 1 3 4
3 7 7 6 7 7 7
Run Code Online (Sandbox Code Playgroud)
这里可以有很多列。
使用数字数据帧执行此操作的一种有效方法是使用标准偏差(仅当所有值都相同时才为 0):
df[df.std(axis=1) > 0]
Out:
A B C D E F
0 1 2 3 1 3 4
3 7 7 6 7 7 7
Run Code Online (Sandbox Code Playgroud)
40k 行的时间:
%timeit df[df.std(axis=1) > 0]
1000 loops, best of 3: 1.69 ms per loop
%timeit df[df.nunique(1)>1]
1 loop, best of 3: 2.62 s per loop
Run Code Online (Sandbox Code Playgroud)
使用nunique
df=df[df.nunique(1)>1]
df
Out[286]:
A B C D E F
index
0 1 2 3 1 3 4
3 7 7 6 7 7 7
Run Code Online (Sandbox Code Playgroud)