在此代码块中寻找更好的python约定

时间:2019-05-21 04:50:14

标签: python pandas

当我在循环中构建数据帧时,我经常会使用以下约定:

complete_df = None
for data_chunk in data_chunks:
    partial_df = get_partial_df(data_chunk)    
    partial_df = do_some_stuff_to_my_df(partial_df)
    if complete_df is None:
        complete_df = partial_df
    else:
        complete_df = complete_df.append(partial_df)

我正在寻找一种更好/更短/更多pythonic的方式来做到这一点。三元声明似乎并没有改善。

3 个答案:

答案 0 :(得分:0)

尝试

complete_df = None
for data_chunk in data_chunks:
    partial_df = get_partial_df(data_chunk)    
    complete_df = partial_df if complete_df is None else complete_df.append(partial_df)

答案 1 :(得分:0)

data_chunks = range(1, 100, 4)

def get_partial_df(num):
    return num

#complete_df = None
complete_df = list()
print(type(complete_df))
for data_chunk in data_chunks:
    partial_df = get_partial_df(data_chunk)
    complete_df.append(partial_df)

    # if complete_df is None:
    #     complete_df = partial_df  ##here complete_df is int
    # else:
    #    complete_df = complete_df.append(partial_df) ## appending to be done on list/tuple.

答案 2 :(得分:0)

如果将What is the correct output? 初始化为空的complete_df,则可以取消if else块:

DataFrame