簡體   English   中英

從具有相同 df 長度的 numpy 數組的字典中將列添加到 Pandas 數據幀的最快/最佳方法?

[英]Fastest/best way to add columns to a pandas dataframe from a dict of numpy arrays with the same df length?

可能是一個簡單的問題,我已經搜索過,但找不到解決方案。

我的代碼是這樣的

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

為什么不簡單:

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

請注意,dict中的數據長度必須等於數據幀中的數據長度

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

嘗試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

使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM