【问题标题】:Optimize dataframe manipulation优化数据框操作
【发布时间】:2019-07-04 00:57:30
【问题描述】:

所以我想优化我的代码,它从 df 中的列在数据框中创建一个新列(具有 ~10^6 行)。我知道,用 axis = 1 应用是不好的。 这是模拟的代码

这是我探索的一些链接。

https://engineering.upside.com/a-beginners-guide-to-optimizing-pandas-code-for-speed-c09ef2c6a4d6 https://maxpowerwastaken.github.io/blog/pandas-dont-apply-_-vectorize/https://tomaugspurger.github.io/modern-4-performance.html

https://pastebin.com/1biaYCaW

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(0,500,size=(10000, 2)), 
                                    columns=list('AB'))
df['C'] = pd.Series(np.random.randint(5,10,size=(10000)))
df['D'] = pd.Series(np.random.randint(1,5,size=(10000)))
df_map = pd.concat([pd.Series(df['D'].unique(), name='D'),
                    pd.Series(np.random.randint(5, 10,size=(4)), name='Map')],
                  axis=1)

def manipulate(b, c, d):
    if b == c:
        return 20
    elif c == df_map[df_map['D'] == d]['Map'].values[0]:
        return 50
    else:
        return 30

__vec_manipulate = np.vectorize(manipulate)
__vec_manipulate(df['B'].values,
                 df['C'].values,
                 df['D'].values)

10^6 行(原始代码)大约需要 16 分钟。 想要改进这一点。

【问题讨论】:

  • 愚蠢的问题:10 lac rows 是什么意思?
  • @QuangHoang 100 万行。印度计量单位。

标签: python pandas optimization


【解决方案1】:

IIUC,这是mapnp.select 问题:

# this will replace the
# c == df_map[df_map['D'] == d]['Map'].values[0]
D_map = df['D'].map(df_map.set_index('D').Map)

# your return column
np.select((df.B.eq(df.C), df.C.eq(D_map)), 
          (20,50), 
          default=30)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    • 2014-01-26
    • 2021-11-13
    • 2011-02-28
    • 2014-06-14
    • 1970-01-01
    相关资源
    最近更新 更多