【发布时间】:2021-01-09 21:06:29
【问题描述】:
我有一个看起来像这样的熊猫数据框:
输入数据框:
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-60 千行。所以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)
关于如何在 pandas 中有效地做到这一点有什么建议吗?
【问题讨论】: