如何使用布尔掩码将pandas数据帧中的“any strings”替换为nan?

2024-05-16 05:34:00 发布

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

我有一个227x4的数据帧,其中有国家名称和数值要清理(wrangle?)。在

以下是数据帧的抽象:

import pandas as pd
import random
import string
import numpy as np
pdn = pd.DataFrame(["".join([random.choice(string.ascii_letters) for i in range(3)]) for j in range (6)], columns =['Country Name'])
measures = pd.DataFrame(np.random.random_integers(10,size=(6,2)), columns=['Measure1','Measure2'])
df = pdn.merge(measures, how= 'inner', left_index=True, right_index =True)

df.iloc[4,1] = 'str'
df.iloc[1,2] = 'stuff'
print(df)

  Country Name Measure1 Measure2
0          tua        6        3
1          MDK        3    stuff
2          RJU        7        2
3          WyB        7        8
4          Nnr      str        3
5          rVN        7        4

如何在所有列中将字符串值替换为np.nan,而不涉及国家名称?在

我试着用布尔掩码:

^{pr2}$

我看了几个与我的问题有关的问题([1][2][3][4][5][6][7][8]),但没有找到一个能回答我的问题。在


Tags: 数据inimport名称dataframedfforstring
3条回答

使用带错误的数字强制,即

cols = ['Measure1','Measure2']
df[cols] = df[cols].apply(pd.to_numeric,errors='coerce')
^{pr2}$

仅指定感兴趣的列:

cols = ['Measure1','Measure2']
mask = df[cols].applymap(lambda x: isinstance(x, (int, float)))

df[cols] = df[cols].where(mask)
print (df)
  Country Name Measure1 Measure2
0          uFv        7        8
1          vCr        5      NaN
2          qPp        2        6
3          QIC       10       10
4          Suy      NaN        8
5          eFS        6        4

A meta-question, Is it normal that it takes me more than 3 hours to formulate a question here (including research) ?

在我看来是的,创造好问题真的很难。在

cols = ['Measure1','Measure2']
df[cols] = df[cols].applymap(lambda x: x if not isinstance(x, str) else np.nan)

或者

^{pr2}$

结果:

In [22]: df
Out[22]:
  Country Name  Measure1  Measure2
0          nBl      10.0       9.0
1          Ayp       8.0       NaN
2          diz       4.0       1.0
3          aad       7.0       3.0
4          JYI       NaN      10.0
5          BJO       9.0       8.0

相关问题 更多 >