【发布时间】:2019-07-16 10:35:10
【问题描述】:
我的目标是使用“模拟”文件来规范“输入”文件。必须这样做的方式是,如果模拟文件中的条目在同一组中并且其位置在位置开始和位置结束之间的间隔中,我必须从data_value 中减去“模拟”分数。
下面我介绍一个简化的案例,实际表格要大得多,我的解决方案不够快。我一直在寻找替代品,但到目前为止似乎没有什么能解决我的问题。我相信有更快的方法来解决这个问题,希望有人能帮助我。
我编写的代码完全符合我的要求:
import pandas as pd
test_in_dict = {'group': [1, 1, 1, 2, 2, 2],
'position_start' :[10,20,30, 40, 50, 60],
'position_end' : [15, 25, 35, 45, 55, 65],
'data_values' : [11, 12, 13, 14, 15, 16]}
test_in = pd.DataFrame(data=test_in_dict)
test_mock_dict = {'group_m': [1, 1, 1, 1, 2, 2, 2, 2],
'position_m' : [11, 16, 20, 52, 42, 47, 12, 65],
'score_m': [1, 1, 2, 1, 3, 1, 2, 1]}
test_mock = pd.DataFrame(data=test_mock_dict)
for index_in, row_in in test_in.iterrows():
for index_m, row_m in test_mock.iterrows():
if (row_in['group'] == row_m['group_m']) & \
(row_m['position_m'] >= row_in['position_start']) & \
(row_m['position_m'] < row_in['position_end']):
row_in['data_values'] = row_in['data_values'] - row_m['score_m']
如何编写与上面代码相同的东西,但避免双循环使我处于 O(NxM) 复杂性中,N 和 M 都很大(模拟文件的条目比 in 文件多)?
【问题讨论】:
-
您不能使用字典按
group或group_m对行进行分组吗? -
如果没有仅使用两个数据框的更优雅、更强大的解决方案,我可能会尝试这样做。我猜这将有助于大大降低复杂性。