小编Twi*_*ins的帖子

熊猫面试问题-比较熊猫加入并理想地提供最快的方法

不久前,我接受了数据科学家职位的采访。奇怪的是,在不询问机器学习或数据科学乃至统计问题的情况下,我被赋予了一项小任务,即将两个熊猫数据框连接起来,并比较各种方法。我没有得到期望的标准。我提供了多种解决方案。令人惊讶的是,之后有人告诉我,我的解决方案均未达到该任务所需其他解决方案的性能基准!显然,我要求提供反馈或他们用于此任务的其他方法优于我提供的解决方案,但请回答;不只是 我认为自己是一名中级Python程序员,并且我当然不了解许多技巧或最佳实践,并且到目前为止,我对性能的关注不是很多,除非它非常慢。因此自面试以来

问题:

# Randomly generated historical data about how many megabytes were downloaded from the Internet."HoD" is the Hour of the Day!
hist_df = pd.DataFrame(columns=['HoD', 'Volume'])
hist_df['HoD'] = np.random.randint(0, 24, 365 * 24)
hist_df['Volume'] = np.random.uniform(1, 1000, 365 * 24)

# Tariffs based on the hour of the day
tariffs_df = pd.DataFrame({
    'Time range': ['00:00 to 09:00', '09:00 to 18:00', '18:00 to 00:00'],
    'cost': [10, 14, 22]
})
Run Code Online (Sandbox Code Playgroud)

任务:返回历史数据框,并带有附加的“费用”列,该列将显示历史数据每小时每小时花费多少钱。基本上,关税数据框架需要合并到历史数据中。

我的解决方案:这是包含我提供的四种方法的要点。我提供了基于(最慢到最快)i)简单迭代(最慢),ii)pandas_apply,iii)和numpy向量化以及iv)pandas binning(最快)的合并。结果为(以秒为单位):

{'naive_iterrows': 5.810565948486328,
 'pandas_apply': 0.6743350028991699, …
Run Code Online (Sandbox Code Playgroud)

python performance merge dataframe pandas

5
推荐指数
1
解决办法
159
查看次数

使用查找数据帧替换数据帧中的值

我想使用查找数据帧替换df数据帧中的值。

import pandas as pd

df=pd.DataFrame({
                  'no1':[20,20,40,10,50],
                  'no2':[50,20,10,40,50],
                  'no3':[30,10,50,40,50]
                  })

   no1  no2 no3
0   20  50  30
1   20  20  10
2   40  10  50
3   10  40  40
4   50  50  50

lookup=pd.DataFrame({'label':['A','B','C','D','E'],
                  'id':[10,20,30,40,50]})

    label id
0   A     10
1   B     20
2   C     30
3   D     40
4   E     50
Run Code Online (Sandbox Code Playgroud)

特别是,我想要:

   no1  no2 no3
0   B   E   C
1   B   B   A
2   D   A   E
3   A   D   D
4   E   E   E …
Run Code Online (Sandbox Code Playgroud)

python lookup pandas

3
推荐指数
2
解决办法
2875
查看次数

标签 统计

pandas ×2

python ×2

dataframe ×1

lookup ×1

merge ×1

performance ×1