我们可以在轴 1 上使用np.unique。不幸的是,没有用于删除重复列的 pandas 内置函数。
df.drop_duplicates 只删除重复的行。
返回删除重复行的 DataFrame。
我们可以围绕np.unique 创建一个函数来删除重复的列。
def drop_duplicate_cols(df):
uniq, idxs = np.unique(df, return_index=True, axis=1)
return pd.DataFrame(uniq, index=df.index, columns=df.columns[idxs])
drop_duplicate_cols(X)
X1 Y1
0 0.0 6.0
1 3.0 7.1
2 7.6 1.2
Online Demo
注意: np.unique docs:
返回数组中排序后的唯一元素。
解决方法:要保留原始顺序,请对idxs 进行排序。
在具有多个dtypes 的数据帧上使用.T 会与您的实际dtypes 混淆。
df = pd.DataFrame({'A': [0, 1], 'B': ['a', 'b'], 'C': [0, 1], 'D':[2.1, 3.1]})
df.dtypes
A int64
B object
C int64
D float64
dtype: object
df.T.T.dtypes
A object
B object
C object
D object
dtype: object
# To get back original `dtypes` we can use `.astype`
df.T.T.astype(df.dtypes).dtypes
A int64
B object
C int64
D float64
dtype: object