如何将pandas数据帧中的字符串设置为另一个值

2024-04-23 08:38:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含字符串和数字的pandas数据帧:

> print(f1)

    0    1
0  Hi    0
1   5  Bye
2   6    9
3   7   10

> print(type(f1))

<class 'pandas.core.frame.DataFrame'>

我想把所有的字符串值都设置为0。也就是说,我希望得到以下输出:

^{pr2}$

我的尝试包括尝试这两种说法

print(f1.select_dtypes(include=[numpy.number]))
print(f1.select_dtypes(exclude=[object]))

但两次我都得到一个空的数据帧作为输出:

Empty DataFrame
Columns: []
Index: [0, 1, 2, 3]

我还能做些什么来获得期望的输出呢?在


Tags: 数据字符串coredataframepandastype数字hi
2条回答

您也可以使用regex,从这里:Regex: How to match a string that is not only numbers。但这不适用于浮动(例如3.14):

df = df.replace(r'(?!^\d+$)^.+$', 0, regex=True).astype(int)

有两种可能的方法:

如果所有值都是字符串,则使用^{}和参数errors='coerce'将字符串替换为NaNs,然后将{a2}替换为^{}

print (df.applymap(type))
               0              1
0  <class 'str'>  <class 'str'>
1  <class 'str'>  <class 'str'>
2  <class 'str'>  <class 'str'>
3  <class 'str'>  <class 'str'>


df = df.apply(lambda x: pd.to_numeric(x, errors='coerce')).fillna(0).astype(int)
print (df)
   0   1
0  0   0
1  5   0
2  6   9
3  7  10

或者如果混合类型使用^{}^{}

^{pr2}$

相关问题 更多 >