天天看点

dataframe 合并_python pandas行列合并的其他技巧

python pandas行列合并的其他技巧​mp.weixin.qq.com

dataframe 合并_python pandas行列合并的其他技巧

pandas中使用append方法,能够快速给dataFrame添加一些rows,或者columns。当然,效率最高的仍然是concat()方法或者merge()方法。

下面介绍一下append合并行:

append方法的官方介绍是这样的:

Append rows of

other

to the end of caller, returning a new object.

Columns in

other

that are not in the caller are added as new columns.

other : DataFrame or Series/dict-like object, or list of these The data to append.

下面举例:

>>> df = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))
    >>> df
       A  B
    0  1  2
    1  3  4
    >>> df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB'))
    # 如果直接append则index的值都不会发生变化
    >>> df.append(df2)
       A  B
    0  1  2
    1  3  4
    0  5  6
    1  7  8
    # 设置ignore_index为true
    >>> df.append(df2, ignore_index=True)
       A  B
    0  1  2
    1  3  4
    2  5  6
    3  7  8
           

下面把othere设置为dict

>>> df = pd.DataFrame(columns=['A'])
    >>> for i in range(5):
            df = df.append({'A': i}, ignore_index=True)
    >>> df
       A
    0  0
    1  1
    2  2
    3  3
    4  4    
    # More efficient(大量数据合并时,官方的推荐方式):
    >>> pd.concat([pd.DataFrame([i], columns=['A']) for i in range(5)],
    ...           ignore_index=True)
       A
    0  0
    1  1
    2  2
    3  3
    4  4
           

哈哈,以上就是python小工具关于append方法的使用的简单技巧,欢迎关注python小工具,一起学习python和pandas