![](/img/trans.png)
[英]python pandas data frame replace ends of string values to another character
[英]Replace all string types in Python Pandas Data Frame with a 1
這是一個奇怪的特定問題,但
如果我的熊貓數據框看起來像:
...
8 0
9 0
10 0
11 0
12 0
13 Dogs
14 Cats
...
我需要它查看所有字符串類型並將其更改為1,因此:
...
8 0
9 0
10 0
11 0
12 0
13 1
14 1
...
有沒有辦法讓df.replace()查看字符串類型?
謝謝!
只要您列中的其他值都是有效的數字值,並且還沒有NaN
值,則可以使用to_numeric
將字符串值強制為數字值,在這種情況下為NaN
。
然后,您可以替換NaN
與1
,但由於引進的NaN
,在dtype
改為float
,所以我們需要區分的dtype
,以int
使用astype
:
In [6]:
# read the data into our df
import pandas as pd
import io
t="""8 0
9 0
10 0
11 0
12 0
13 Dogs
14 Cats"""
df = pd.read_csv(io.StringIO(t), delim_whitespace=True, header=None)
df
Out[6]:
0 1
0 8 0
1 9 0
2 10 0
3 11 0
4 12 0
5 13 Dogs
6 14 Cats
現在轉換字符串,將其替換為1
並將Series dtype強制轉換回int:
In [7]:
df[1] = pd.to_numeric(df[1], errors='coerce').fillna(1).astype(int)
df
Out[7]:
0 1
0 8 0
1 9 0
2 10 0
3 11 0
4 12 0
5 13 1
6 14 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.