【问题标题】:Fastest/best way to add columns to a pandas dataframe from a dict of numpy arrays with the same df length?从具有相同df长度的numpy数组的字典中将列添加到pandas数据帧的最快/最佳方法?
【发布时间】:2020-09-17 16:42:35
【问题描述】:

可能是一个简单的问题,我已经搜索过但我找不到解决方案。

我的代码是这样的

data_df = pd.DataFrame([
    ['2012-02-22', '3', 'a', 6],
    ['2012-02-23', '3.2', 'g', 8],
    ['2012-02-24', '5.2', 'l', 2],
    ['2012-02-25', '1.4', 'i', 4]],
    columns=['date', '1', '2', '3'])
dict_a = {
    'a': np.array([False, True, False, False], dtype='bool'),
    'b': np.array([True, True, False, False], dtype='bool'),
    'c': np.array([False, True, True, False], dtype='bool'),
}

我想要一个这样的df

              1  2  3      a      b      c
date                                      
2012-02-22    3  a  6  False   True  False
2012-02-23  3.2  g  8   True   True   True
2012-02-24  5.2  l  2  False  False   True
2012-02-25  1.4  i  4  False  False  False

到目前为止,我发现最好的方法是这样,但对我来说似乎很老套

data_df = data_df.set_index('date')
df_dict = pd.DataFrame.from_dict(dict_a)
df_dict['date'] = data_df.index
df_dict = df_dict.set_index('date')
df_new = pd.merge(data_df, df_dict, left_index=True, right_index=True)

有更快/更好的方法来实现它吗?

编辑:结果

感谢大家的快速响应。 我已经做了一些时间安排,(到目前为止)看起来给定数据最快的是第一个。

def df_new1():
    data_df = pd.DataFrame([
        ['2012-02-22', '3', 'a', 6],
        ['2012-02-23', '3.2', 'g', 8],
        ['2012-02-24', '5.2', 'l', 2],
        ['2012-02-25', '1.4', 'i', 4]],
        columns=['date', '1', '2', '3'])

    dict_a = {
        'a1': np.array([False, True, False, False], dtype='bool'),
        'b1': np.array([True, True, False, False], dtype='bool'),
        'c1': np.array([False, True, True, False], dtype='bool'),
    }
    return pd.concat((data_df, pd.DataFrame(dict_a)), axis=1).set_index('date')


def df_new2():
    data_df = pd.DataFrame([
        ['2012-02-22', '3', 'a', 6],
        ['2012-02-23', '3.2', 'g', 8],
        ['2012-02-24', '5.2', 'l', 2],
        ['2012-02-25', '1.4', 'i', 4]],
        columns=['date', '1', '2', '3'])

    dict_a = {
        'a1': np.array([False, True, False, False], dtype='bool'),
        'b1': np.array([True, True, False, False], dtype='bool'),
        'c1': np.array([False, True, True, False], dtype='bool'),
    }
    return data_df.assign(**dict_a).set_index('date')


def df_new3():
    data_df = pd.DataFrame([
        ['2012-02-22', '3', 'a', 6],
        ['2012-02-23', '3.2', 'g', 8],
        ['2012-02-24', '5.2', 'l', 2],
        ['2012-02-25', '1.4', 'i', 4]],
        columns=['date', '1', '2', '3'])

    dict_a = {
        'a1': np.array([False, True, False, False], dtype='bool'),
        'b1': np.array([True, True, False, False], dtype='bool'),
        'c1': np.array([False, True, True, False], dtype='bool'),
    }
    return data_df.join(pd.DataFrame(dict_a)).set_index('date')


def df_new4():
    data_df = pd.DataFrame([
        ['2012-02-22', '3', 'a', 6],
        ['2012-02-23', '3.2', 'g', 8],
        ['2012-02-24', '5.2', 'l', 2],
        ['2012-02-25', '1.4', 'i', 4]],
        columns=['date', '1', '2', '3'])

    dict_a = {
        'a1': np.array([False, True, False, False], dtype='bool'),
        'b1': np.array([True, True, False, False], dtype='bool'),
        'c1': np.array([False, True, True, False], dtype='bool'),
    }
    for keys in dict_a:
        data_df[keys] = dict_a[keys]
    return data_df.set_index('date')

print('df_new1', timeit(df_new1, number=1000))
print('df_new2', timeit(df_new2, number=1000))
print('df_new3', timeit(df_new3, number=1000))
print('df_new4', timeit(df_new4, number=1000))
df_new1 2.0431520210004237
df_new2 2.6708478379987355
df_new3 2.4773063749998983
df_new4 2.910699995998584

【问题讨论】:

    标签: python pandas performance dataframe coding-style


    【解决方案1】:

    pd.concat on axis=1,然后设置索引

    pd.concat((data_df,pd.DataFrame(dict_a)),axis=1).set_index("date")
    
                  1  2  3      a      b      c
    date                                      
    2012-02-22    3  a  6  False   True  False
    2012-02-23  3.2  g  8   True   True   True
    2012-02-24  5.2  l  2  False  False   True
    2012-02-25  1.4  i  4  False  False  False
    

    【讨论】:

    • 看起来这是给定数据下最快的代码。感谢您的帮助!
    【解决方案2】:

    为什么不简单:

    for keys in dict_a:
        data_df[keys]=dict_a[keys]
    

    请注意,dict中的数据长度必须等于dataframe中的数据长度

    【讨论】:

    • 我接受这个结果,因为目前看起来是最快的。感谢您的帮助!
    • 对不起,我犯了一个错误。我忘了在末尾添加.set_index('date'),因为所需的代码有它。看起来这个小改动增加了很多工作,现在代码是最慢的。 :-/
    【解决方案3】:

    试试DataFrame.assign:

    data_df.assign(**dict_a)
    

             date    1  2  3      a      b      c
    0  2012-02-22    3  a  6  False   True  False
    1  2012-02-23  3.2  g  8   True   True   True
    2  2012-02-24  5.2  l  2  False  False   True
    3  2012-02-25  1.4  i  4  False  False  False
    

    【讨论】:

    • 这非常优雅和干净,我可能会使用它,因为它是最简洁的。谢谢!
    【解决方案4】:

    使用join:

    data_df.join(pd.DataFrame(dict_a)).set_index('date')
                  1  2  3      a      b      c
    date                                      
    2012-02-22    3  a  6  False   True  False
    2012-02-23  3.2  g  8   True   True   True
    2012-02-24  5.2  l  2  False  False   True
    2012-02-25  1.4  i  4  False  False  False
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-06
      • 2016-08-01
      • 2014-07-16
      • 1970-01-01
      • 1970-01-01
      • 2014-10-28
      • 2021-11-11
      相关资源
      最近更新 更多