- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
此循环旨在以 1:4 的比例将 df2 中的主题与 df1 中的主题进行匹配。这里的关键是随机选择主题,同时避免冗余。任何主题都不应匹配两次。 df1 有几千个主题,而 df2 有超过一百万个。 df1 中的每个科目都将与 df2 中的四个科目匹配,不匹配的将被排除在外。有没有人有提高效率的想法?一种还可以节省 RAM 的方法将是理想的。谢谢。
for x in range(4): # 1:4 matching
for index, row in df1.iterrows():
temp = df2.loc[(df2['matched'] != 1) & (df2['race_ethnicity'] == row['race_ethnicity']) & (df2['age'] == row['age']) & ((df2['date1'] > row['date2']) | (df2['date1'].isna()))]
a = temp.sample()
a['matched_subject'] = row['subject_id']
a['matched'] = '1'
a['possible_matches'] = len(temp)
它可以简化为这个,但我更愿意继续使用 'possible_matches' 行进行诊断。
for x in range(4): # 4 because 1:4 matching
for index, row in df1.iterrows():
a = df2.loc[(df2['matched_subject']=='') & (df2['race_ethnicity'] == row['race_ethnicity']) & (df2['age'] == row['age']) & ((df2['date1'] > row['date2']) | (df2['date1'] == 0))].sample()
a['matched_subject'] = row['pid']
说明:所有行在两个 DataFrame 中都是唯一的,代表将在生存分析中进行比较的主题列表。 Date1 是结果变量事件的日期时间,存在于两个 DataFrame 中的一小部分主题中。日期 2 是自变量事件的日期时间,适用于所有 df1 科目,没有 df2 科目。示例输入包括:
最佳答案
首先让我们定义一些辅助函数:
def generate_data(df1_len, df2_len, seed=42):
"""Generate random data to help test different algorithms"""
np.random.seed(seed)
d2 = np.random.randint(0, 3000, size=df1_len)
df1 = pd.DataFrame({
'subject_id': np.arange(df1_len),
'race_ethnicity': np.random.choice(list('ABC'), df1_len),
'age': np.random.randint(18, 100, df1_len),
'date2': pd.Timestamp('2000-01-01') + pd.to_timedelta(d2, unit='D')
})
d1 = np.random.randint(0, 3000, size=int(df2_len * np.random.rand()))
d1 = np.hstack([d2, np.repeat(np.nan, df2_len - len(d1))])
df2 = pd.DataFrame({
'subject_id': np.arange(df2_len),
'race_ethnicity': np.random.choice(list('ABC'), df2_len),
'age': np.random.randint(18, 100, df2_len),
'date1': pd.Timestamp('2000-01-01') + pd.to_timedelta(d1, unit='D')
})
return df1, df2
def verify(df1, df2):
"""Verify that df1 and df2 are matched according to predefined rules"""
tmp = df1.merge(df2, how='left', left_on='subject_id', right_on='matched_subject', suffixes=('_1', "_2"))
assert (tmp['race_ethnicity_1'] == tmp['race_ethnicity_2']).all(), 'race_ethnicity does not match'
assert (tmp['age_1'] == tmp['age_2']).all(), 'age does not match'
assert ((tmp['date1'] > tmp['date2']) | tmp['date1'].isna()).all(), 'date1 must be NaT or grater than date2'
assert tmp.groupby('matched_subject').size().eq(4).all(), 'Invalid match ratio'
print('All is good')
原来的解决方案
df1, df2 = generate_data(500, 100_000)
df2['matched'] = False
df2['matched_subject'] = None
df2['possible_matches'] = None
for x in range(4): # 1:4 matching
for index, row in df1.iterrows():
cond = (
(df2['matched'] != 1) &
(df2['race_ethnicity'] == row['race_ethnicity']) &
(df2['age'] == row['age']) &
((df2['date1'] > row['date2']) | df2['date1'].isna())
)
temp = df2.loc[cond]
if temp.empty:
continue
idx = temp.sample().index
df2.loc[idx, 'matched_subject'] = row['subject_id']
df2.loc[idx, 'matched'] = True
df2.loc[idx, 'possible_matches'] = len(temp)
改进版
for _ in range(4)
),可以提高性能
df1, df2 = generate_data(5000, 1_000_000)
df2['matched'] = False
df2['matched_subject'] = None
df2['possible_matches'] = None
for index, row in df1.iterrows():
cond = (
(df2['matched'] != 1) &
(df2['race_ethnicity'] == row['race_ethnicity']) &
(df2['age'] == row['age']) &
((df2['date1'] > row['date2']) | df2['date1'].isna())
)
temp = df2.loc[cond]
if temp.empty:
continue
idx = temp.sample(4).index
df2.loc[idx, 'matched_subject'] = row['subject_id']
df2.loc[idx, 'matched'] = True
df2.loc[idx, 'possible_matches'] = len(temp)
进一步改进的版本
df1, df2 = generate_data(500, 100_000)
# Shuffle df2 so the matches will be random
df2 = df2.sample(frac=1)
# A dictionary to hold the result. Its keys are the indexes in df2 and its
# values are the indexes of df1
matches = {}
# We loop by group instead of individual row
grouped1 = df1.groupby(['race_ethnicity', 'age', 'date2'])
grouped2 = df2.groupby(['race_ethnicity', 'age'])
for (race_ethnicity, age, date2), subset1 in grouped1:
# Get all rows from df2 that have the same `race_ethnicity` and `age`
subset2 = grouped2.get_group((race_ethnicity, age))
# pd.Series is slow. Switch to np.array for speed
index2 = subset2.index.to_numpy()
date1 = subset2['date1'].to_numpy()
# Since all rows in subset1 and subset2 have already had the same
# `race_ethnicity` and `age`, we only need to filter for two things:
# 1. The relationship between `date1` and `date2`; and
# 2. That the row in `df2` has NOT been matched before
cond = (
(np.isnan(date1) | (date1 > date2))
& np.isin(index2, list(matches.keys()), invert=True)
)
# The match ratio
index1 = np.repeat(subset1.index.to_numpy(), 4)
# There is no way to know in advance how many rows in `subset2` will meet
# the matching criteria:
# * Ideally: cond.sum() == len(index1), ie. 4 rows in `subset2` for every
# row in `subset1`
# * If there are more matches than we need: we will take the first `4 *
# len(subset1)` rows
# * If there are not enough matches: eg. 6 rows in `subset2` for 2 rows in
# `subset1`, some rows in `subset1` will have to accept < 4 matches
n = min(cond.sum(), len(index1))
matches.update({
key: value for key, value in zip(index2[cond][:n], index1[:n])
})
tmp = pd.DataFrame({
'index2': matches.keys(),
'index1': matches.values()
})
df2 = (
df2.merge(tmp, how='left', left_index=True, right_on='index2')
.merge(df1['subject_id'].to_frame('matched_subject'), how='left', left_on='index1', right_index=True)
.drop(columns=['index1', 'index2'])
)
您可以验证解决方案:
verify(df1, df2)
# Output: All is good
关于python - 有没有办法矢量化这个函数或提高它的效率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69036508/
我正在处理一组标记为 160 个组的 173k 点。我想通过合并最接近的(到 9 或 10 个组)来减少组/集群的数量。我搜索过 sklearn 或类似的库,但没有成功。 我猜它只是通过 knn 聚类
我有一个扁平数字列表,这些数字逻辑上以 3 为一组,其中每个三元组是 (number, __ignored, flag[0 or 1]),例如: [7,56,1, 8,0,0, 2,0,0, 6,1,
我正在使用 pipenv 来管理我的包。我想编写一个 python 脚本来调用另一个使用不同虚拟环境(VE)的 python 脚本。 如何运行使用 VE1 的 python 脚本 1 并调用另一个 p
假设我有一个文件 script.py 位于 path = "foo/bar/script.py"。我正在寻找一种在 Python 中通过函数 execute_script() 从我的主要 Python
这听起来像是谜语或笑话,但实际上我还没有找到这个问题的答案。 问题到底是什么? 我想运行 2 个脚本。在第一个脚本中,我调用另一个脚本,但我希望它们继续并行,而不是在两个单独的线程中。主要是我不希望第
我有一个带有 python 2.5.5 的软件。我想发送一个命令,该命令将在 python 2.7.5 中启动一个脚本,然后继续执行该脚本。 我试过用 #!python2.7.5 和http://re
我在 python 命令行(使用 python 2.7)中,并尝试运行 Python 脚本。我的操作系统是 Windows 7。我已将我的目录设置为包含我所有脚本的文件夹,使用: os.chdir("
剧透:部分解决(见最后)。 以下是使用 Python 嵌入的代码示例: #include int main(int argc, char** argv) { Py_SetPythonHome
假设我有以下列表,对应于及时的股票价格: prices = [1, 3, 7, 10, 9, 8, 5, 3, 6, 8, 12, 9, 6, 10, 13, 8, 4, 11] 我想确定以下总体上最
所以我试图在选择某个单选按钮时更改此框架的背景。 我的框架位于一个类中,并且单选按钮的功能位于该类之外。 (这样我就可以在所有其他框架上调用它们。) 问题是每当我选择单选按钮时都会出现以下错误: co
我正在尝试将字符串与 python 中的正则表达式进行比较,如下所示, #!/usr/bin/env python3 import re str1 = "Expecting property name
考虑以下原型(prototype) Boost.Python 模块,该模块从单独的 C++ 头文件中引入类“D”。 /* file: a/b.cpp */ BOOST_PYTHON_MODULE(c)
如何编写一个程序来“识别函数调用的行号?” python 检查模块提供了定位行号的选项,但是, def di(): return inspect.currentframe().f_back.f_l
我已经使用 macports 安装了 Python 2.7,并且由于我的 $PATH 变量,这就是我输入 $ python 时得到的变量。然而,virtualenv 默认使用 Python 2.6,除
我只想问如何加快 python 上的 re.search 速度。 我有一个很长的字符串行,长度为 176861(即带有一些符号的字母数字字符),我使用此函数测试了该行以进行研究: def getExe
list1= [u'%app%%General%%Council%', u'%people%', u'%people%%Regional%%Council%%Mandate%', u'%ppp%%Ge
这个问题在这里已经有了答案: Is it Pythonic to use list comprehensions for just side effects? (7 个答案) 关闭 4 个月前。 告
我想用 Python 将两个列表组合成一个列表,方法如下: a = [1,1,1,2,2,2,3,3,3,3] b= ["Sun", "is", "bright", "June","and" ,"Ju
我正在运行带有最新 Boost 发行版 (1.55.0) 的 Mac OS X 10.8.4 (Darwin 12.4.0)。我正在按照说明 here构建包含在我的发行版中的教程 Boost-Pyth
学习 Python,我正在尝试制作一个没有任何第 3 方库的网络抓取工具,这样过程对我来说并没有简化,而且我知道我在做什么。我浏览了一些在线资源,但所有这些都让我对某些事情感到困惑。 html 看起来
我是一名优秀的程序员,十分优秀!