我正在嘗試將 Pandas 資料框與串列進行比較。我已將 ID 提取到一個名為 list_x 的串列中;
由于我有幾行具有相同的 ID,這反映在串列中。即list_x = [1,1,1,1,2,3等]
我正在嘗試洗掉所有 ID 也在串列中的資料框條目
what I have been trying are variations of:
for j in range(len(dataframe)-1):
if dataframe.loc(j,"ID") in list_x: dataframe.drop([j], inplace = True)
or variations of
for j in range(len(dataframe)-1):
for k in range(len(list_x)-1):
if dataframe.loc(j,"ID") in list_x[k]: dataframe.drop([j], inplace = True)
I get an error which I think comes from the fact I am comparing the list's index with the dataframe, and not the actual list entry.
Any help would be appreciated. I do realize code snippets are discouraged, but I would appreciate an example if possible! Thanks in advance :)
uj5u.com熱心網友回復:
您想要獲取沒有與 list_x 中的 ID 關聯的行的資料框。所以你可以這樣做:
您的 df(2 列:ID 和值)
df = pd.DataFrame({'ID': [1,3,5,6,7], 'value': ['red', 'blue', 'green', 'orange', 'purple']})
資料框中不需要的 ID 串列
list_x = [1,1,2,3,5]
輸出
df = df[~df.ID.isin(list_x)]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/526494.html
下一篇:名稱“”未定義-python
