如何洗掉 A 列,因為它在 python 中有以下“https://”?
背景故事:我有一個 500 列的資料框,其中 250 列是行中的“https://”鏈接,解釋了先前的變數是什么。
目標是遍歷 df 以洗掉具有“http://”的列
| 一種 | 乙 |
|---|---|
| https://我的網站 | 25 |
| https://我的網站 | 42 |
我想要的輸出是:
| 乙 |
|---|
| 25 |
| 42 |
uj5u.com熱心網友回復:
下面的代碼片段應該可以作業,洗掉所有包含 url 的列:
to_drop = []
for column in df:
try:
has_url = df[column].str.startswith('https://').any()
except AttributeError:
pass # dtype is not string
if has_url:
to_drop.append(column)
df.drop(columns=to_drop, inplace=True)
對于每一列,它檢查每一行是否以“https://”開頭。如果其中任何一個這樣做,則將它們添加到要洗掉的列的“to_drop”串列中。然后此串列中的列被洗掉。
如果其中至少 50% 的值是 URL,則以下版本只會洗掉一列:
to_drop = []
for column in df:
try:
has_url = df[column].str.startswith('https://').mean() > 0.5
except AttributeError:
pass # dtype is not string
if has_url:
to_drop.append(column)
df.drop(columns=to_drop, inplace=True)
您可以將0.5更改為0到1之間的另一個數字,以更改 URL 應占多大百分比以便洗掉列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/447967.html
