我有一个227x4 DataFrame,国家名称和数值要清理(争吵?)。
这是DataFrame的抽象:
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
替换字符串值?
我尝试使用布尔掩码:
mask = df.loc[:,measures.columns].applymap(lambda x: isinstance(x, (int, float))).values
print(mask)
[[ True True]
[ True False]
[ True True]
[ True True]
[False True]
[ True True]]
# I thought the following would replace by default false with np.nan in place, but it didn't
df.loc[:,measures.columns].where(mask, inplace=True)
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
# this give a good output, unfortunately it's missing the country names
print(df.loc[:,measures.columns].where(mask))
Measure1 Measure2
0 6 3
1 3 NaN
2 7 2
3 7 8
4 NaN 3
5 7 4
我查看过与我有关的几个问题([1],[2],[3],[4],[5],[6],{ {3}},[7]),但找不到能回答我关注的问题。
答案 0 :(得分:8)
cols = ['Measure1','Measure2']
df[cols] = df[cols].applymap(lambda x: x if not isinstance(x, str) else np.nan)
或
df[cols] = df[cols].applymap(lambda x: np.nan if isinstance(x, str) else x)
结果:
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
答案 1 :(得分:5)
仅分配感兴趣的列:
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
一个元问题,在这里(包括研究)制定问题花了我3个多小时是否正常?
在我看来,创造好问题真的很难。
答案 2 :(得分:5)
使用带错误的数字强制,即
cols = ['Measure1','Measure2']
df[cols] = df[cols].apply(pd.to_numeric,errors='coerce')
Country Name Measure1 Measure2 0 PuB 7.0 6.0 1 JHq 2.0 NaN 2 opE 4.0 3.0 3 pxl 3.0 6.0 4 ouP NaN 4.0 5 qZR 4.0 6.0