![](/img/trans.png)
[英]Dropping all rows in pandas having same values in one column and different values in another
[英]Dropping Column with all distinct values in pandas
如果所有值都是不同的並且沒有重復,我想從數據框中刪除一列。
例如:
ID NAME VALUE1 VALUE2 VALUE3
0 1 Alpha 100 A1 ULV
1 2 Alpha 100 A1 SMU
2 3 Alpha 200 A2 UT
列 ID 將被刪除,因為沒有重復值,它會變成這樣:
NAME VALUE1 VALUE2 VALUE3
0 Alpha 100 A1 ULV
1 Alpha 100 A1 SMU
2 Alpha 200 A2 UT
我怎么能這樣做?
您可以使用列表推導來檢查每列是否有重復項:
import pandas
# Recreate example dataframe
df = pandas.DataFrame({
'ID': [1,2,3],
'NAME': ['Alpha', 'Alpha', 'Alpha'],
'VALUE1': [100, 100, 200],
'VALUE2': ['A1', 'A1', 'A2'],
'VALUE3': ['ULV', 'SMU', 'UT'],
})
df = df[[col for col in df.columns if df[col].duplicated().any()]]
輸出:
NAME VALUE1 VALUE2
0 Alpha 100 A1
1 Alpha 100 A1
2 Alpha 200 A2
max_ = max(df.nunique().to_list())
cols = []
for i, (key, val) in enumerate(df.nunique().to_dict().items()):
if val != max_:
cols.append(key)
df = df[[col for col in cols]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.