[英]How to add a column to a DataFrame that contains the name of the group to which a column value corresponds in pandas
[英]How to drop a column in a Pandas DataFrame which contains the same value
我有一個 Pandas DataFrame,其中的一些列在每一行中都具有相同的值。
所以像: -
Col1 Col2 Col3 .... ColX ColY ColZ
323 False 324 4 abc Sync
232 False 342 4 def Sync
364 False 2343 4 ghi Sync
所以我想從上面的 DataFrame 中刪除 Col2、ColX 和 ColZ。
您可以將 DataFrame 與特定行進行比較(我使用df.iloc[0]
選擇了第一行)並使用loc
選擇滿足您指定條件的列:
df.loc[:, ~(df == df.iloc[0]).all()]
Out:
Col1 Col3 ColY
0 323 324 abc
1 232 342 def
2 364 2343 ghi
時間:
@root 的建議nunique
比將 Series 與單個值進行比較要快得多。 除非您有大量列(例如數千個),否則@MMF 建議的列迭代看起來是一種更有效的方法。
df = pd.concat([df]*10**5, ignore_index=True)
%timeit df.loc[:, ~(df == df.iloc[0]).all()]
1 loop, best of 3: 377 ms per loop
%timeit df[[col for col in df if not df[col].nunique()==1]]
10 loops, best of 3: 35.6 ms per loop
df = pd.concat([df]*10, axis=1, ignore_index=True)
%timeit df.loc[:, ~(df == df.iloc[0]).all()]
1 loop, best of 3: 3.71 s per loop
%timeit df[[col for col in df if not df[col].nunique()==1]]
1 loop, best of 3: 353 ms per loop
df = pd.concat([df]*3, axis=1, ignore_index=True)
%timeit df.loc[:, ~(df == df.iloc[0]).all()]
1 loop, best of 3: 11.3 s per loop
%timeit df[[col for col in df if not df[col].nunique()==1]]
1 loop, best of 3: 1.06 s per loop
您還可以檢查由每列的值生成的集合的長度:
df = df[[col for col in df if not len(set(df[col]))==1]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.