假設我有一個x包含 column的資料框terms。術語應該是字串型別,但有些包含數字,因此我想洗掉資料terms框中相應值為整數/浮點數的行。我嘗試了以下但收到一個Key Error:
x = x.drop(x[type(x['terms']) is int].index)
我應該如何更改代碼?
uj5u.com熱心網友回復:
使用pd.to_numeric:
df = pd.DataFrame({'terms': [13, 0.23, 'hello', 'world', '12', '0.45']})
df = df[pd.to_numeric(df['terms'], errors='coerce').isna()]
print(df)
# Output:
terms
2 hello
3 world
細節:
>>> df
terms
0 13
1 0.23
2 hello
3 world
4 12
5 0.45
>>> pd.to_numeric(df['terms'], errors='coerce')
0 13.00
1 0.23
2 NaN
3 NaN
4 12.00
5 0.45
Name: terms, dtype: float64
uj5u.com熱心網友回復:
假設你有一個這樣的資料框:
df = pd.DataFrame({'a':[1,'sd','sf',2,5,'13','s','143f','d234f','z24']})
# notice 13 is a string here ^^^^
a
0 1
1 sd
2 sf
3 2
4 5
5 13
6 s
7 143f
8 d234f
9 z24
如果您想洗掉看起來像數字但實際上是字串的專案,請使用以下命令:
df = df[~df['a'].astype(str).str.isdigit()]
輸出:
>>> df
a
1 sd
2 sf
6 s
7 143f
8 d234f
9 z24
如果您想洗掉實際上根本不是字串的專案,請使用以下命令:
df = df[df['a'].transform(type).eq(str)]
輸出:
>>> df
a
1 sd
2 sf
5 13 <--- Notice how the string '13' is kept
6 s
7 143f
8 d234f
9 z24
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/367722.html
下一篇:如何使用熊貓從網站獲取所有表格
