python - 用单独的浮点值替换出现在熊猫数据框中的每个字符串值
问题描述
我有一个看起来像这样的熊猫数据框:
输入数据框:
A B C
0 m h c
1 l c m
2 h m l
3 c l h
4 m c m
我想用给定范围内的浮点数替换每个l、m、h 和 c值的每次出现。每个字符串的取值范围如下:
范围:
l: 0.0 - 0.25
m: 0.25 - 0.5
h: 0.5 - 0.75
c: 0.75 - 1.0
每次出现都应具有给定范围内的值,但不应重复。转换后的示例输出数据框应如下所示:
输出数据框:
A B C
0 0.31 0.51 0.76
1 0.12 0.56 0.28
2 0.61 0.35 0.21
3 0.8 0.16 0.71
4 0.46 0.72 0.37
我尝试了一种使用transform
. 但它不能完全工作,因为值在列中重复:
def _foo(col):
w = {'l': np.random.uniform(0.0,0.25),
'm':np.random.uniform(0.25,0.5),
'h': np.random.uniform(0.5,0.75),
'c':np.random.uniform(0.75,1.0)}
col = col.replace(w)
return col
df = df.transform(_foo)
如果我使用apply
方法,那么也会发生同样的问题,并且值会沿行重复。它也没有很好的性能,因为实际的数据帧有 50-60000 行。所以apply
会运行很多次。
def _bar(row):
w = {'l': np.random.uniform(0.0,0.25),
'm':np.random.uniform(0.25,0.5),
'h': np.random.uniform(0.5,0.75),
'c':np.random.uniform(0.75,1.0)}
row= row.replace(w)
return row
df = df.apply(_bar, axis=1)
关于如何在熊猫中有效地做到这一点有什么建议吗?
解决方案
这是一种针对性能的矢量化方法:
def map_by_val(df, l):
# dictionary to map dataframe values to index
d = {j:i for i,j in enumerate(l)}
# replace using dictionary
a = df.replace(d).to_numpy()
# since the ranges are a sequence, we can create a
# linspace, and divide in 10 bins each range
rep = np.linspace(0.0, 1.0, 40).reshape(4,-1)
# random integer indexing in each rows
ix = np.random.randint(0,rep.shape[1],a.shape)
# advanced indexing of the array using random integers per row
out = rep[a.ravel(), ix.ravel()].reshape(a.shape).round(2)
return pd.DataFrame(out)
l = ['l','m','h','c']
map_by_val(df, l)
0 1 2
0 0.49 0.74 0.87
1 0.23 0.90 0.49
2 0.67 0.49 0.18
3 0.79 0.21 0.56
4 0.46 0.87 0.36
基准
不幸的是,该对象dtype
限制了矢量化方法的性能,因为最初DataFrame.replace
调用该对象以使用字典映射值。这个答案和stack+groupby
答案的表现都非常相似:
l = ['l','m','h','c']
ranges = {'l': (0,0.25),
'm': (0.25, 0.5),
'h': (0.5,0.75),
'c':(0.75,1)}
def get_rand(x):
lower, upper = ranges[x.iloc[0]]
return np.random.uniform(lower, upper, len(x))
def stack_groupby(df):
s = df.stack()
return s.groupby(s).transform(get_rand).unstack()
plt.figure(figsize=(12,6))
perfplot.show(
setup=lambda n: pd.concat([df]*n, axis=0).reset_index(drop=True),
kernels=[
lambda s: s.applymap(lambda x : np.random.uniform(*ranges[x],1)[0]),
lambda s: map_by_val(s, l),
lambda s: stack_groupby(s)
],
labels=['applymap', 'map_by_val', 'stack_groupby'],
n_range=[2**k for k in range(0, 17)],
xlabel='N',
equality_check=None
)
推荐阅读
- encryption - 在(自制)公钥/私钥基础设施中创建多个共享秘密
- gpu - 带有 openACC 指针的嵌套类
- python - 如何发送密件抄送而不在电子邮件标题中显示密件抄送?
- java - JavaFX 客户端服务器套接字
- cmake - 使用 cmake 从源安装“darktable”时 WEBP 和 LENSFUN 出现问题
- python - 如何修复 NameError:未定义名称“policydict”
- sql - SQL Server:检查每个用户的重复外键(给定合成主键)
- javascript - JavaScript clearInterval 是异步的吗?
- css - 移动响应表
- python - 为什么 Flask 重定向到“GET /?HTTP/1.1”