我有一个字符串数组,可以包含重复的条目。我需要将每个唯一的字符串随机重新分配给数组中另一个随机选择的字符串的所有位置,记住具有多个原始位置的字符串可以映射到一个新位置,反之亦然。实际上,我重新分配了数组中的键,但保留了键的原始分布。
我有一个适用于混合输入类型的有效的Pandas & numpy实现,但它在规模上效率很低,因为它循环遍历每个唯一的值(我需要这个来有效地处理最小的1m+值,理想情况下更多)。这里最慢的部分是枚举本身:
def shuffle_fields(series):
# Create a copy of the original series.
_series = series.copy()
# Get non-NaN keys of original data.
keys = series[pd.notnull(_series)].unique()
# Create a copy of these keys.
_keys = np.copy(keys)
# Shuffle the copy.
np.random.shuffle(_keys)
# Iterate over all zipped keys and set values in copy of series.
for i, (val, new) in enumerate(zip(keys, _keys)):
# Need to key off series as _series is being changed during the loop.
_series.loc[series == val] = new
return _series
示例输入:
_input = pd.Series(['One', 'One', np.NaN, 2, np.NaN, True, 2, 2, 'One', 'One'])
预期输出:
output = pd.Series([2, 2, np.NaN, True, np.NaN, 'One', True, True, 2, 2])
对任何将在规模上工作的实现的建议都是开放的。我并不需要某种可以处理混合数据类型的东西(就像上面的例子一样),但这是一个不错的奖励。该技术必须能够处理null/NaN值,即NaN值应保持不变。
发布于 2019-07-12 02:28:02
假设您可以基于对象的字符串表示来比较是否相等,这是可行的:
import numpy as np
import pandas as pd
np.random.seed(0)
_input = pd.Series(['One', 'One', np.NaN, 2, np.NaN, True, 2, 2, 'One', 'One'])
v = _input.values
uniq, idx = np.unique(v.astype(str), return_inverse=True)
r = np.random.permutation(len(uniq))
output = pd.Series(uniq[r[idx]])
print(output)
# 0 nan
# 1 nan
# 2 2
# 3 True
# 4 2
# 5 One
# 6 True
# 7 True
# 8 nan
# 9 nan
# dtype: object
https://stackoverflow.com/questions/56994657
复制相似问题