pandas.DataFrame.append

来源:互联网 发布:阿里云测试培训 编辑:程序博客网 时间:2024/05/18 03:34

方法

DataFrame.append(other, ignore_index=False, verify_integrity=False)

ignore_index 参数

ignore_index=False

[In]:df = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))[Out]:   A  B0  1  21  3  4[In]:df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB'))[In]:df.append(df2)[Out]:   A  B0  1  21  3  40  5  61  7  8

ignore_index=True

[In]:df.append(df2, ignore_index=True)[Out]:   A  B0  1  21  3  42  5  63  7  8

添加常数报错处理方法

如果直接添加常数会报错.

import pandas as pddf = pd.DataFrame({    "name": [],    "age": []    })----------[In]:df.append(pd.DataFrame({    "name": "nike",    "age": "1"   }))---------------------------------------------------------------------------ValueError                                Traceback (most recent call last)<ipython-input-2-3f8cde4a53ba> in <module>()      1 df.append(pd.DataFrame({      2     "name": "nike",----> 3     "age": "1"      4 }))E:\wang\Anaconda3\lib\site-packages\pandas\core\frame.py in __init__(self, data, index, columns, dtype, copy)    264                                  dtype=dtype, copy=copy)    265         elif isinstance(data, dict):--> 266             mgr = self._init_dict(data, index, columns, dtype=dtype)    267         elif isinstance(data, ma.MaskedArray):    268             import numpy.ma.mrecords as mrecordsE:\wang\Anaconda3\lib\site-packages\pandas\core\frame.py in _init_dict(self, data, index, columns, dtype)    400             arrays = [data[k] for k in keys]    401 --> 402         return _arrays_to_mgr(arrays, data_names, index, columns, dtype=dtype)    403     404     def _init_ndarray(self, values, index, columns, dtype=None, copy=False):E:\wang\Anaconda3\lib\site-packages\pandas\core\frame.py in _arrays_to_mgr(arrays, arr_names, index, columns, dtype)   5396     # figure out the index, if necessary   5397     if index is None:-> 5398         index = extract_index(arrays)   5399     else:   5400         index = _ensure_index(index)E:\wang\Anaconda3\lib\site-packages\pandas\core\frame.py in extract_index(data)   5435    5436         if not indexes and not raw_lengths:-> 5437             raise ValueError('If using all scalar values, you must pass'   5438                              ' an index')   5439 ValueError: If using all scalar values, you must pass an index

将常数转换为列表

[In]:df.append(pd.DataFrame({    "name": ["nike"],    "age": ["1"]   }))[Out]:    age name0   1   nike

给添加的数据框添加索引,注意索引是列表形式

[In]:df.append(pd.DataFrame({    "name": "nike",    "age": "1"   },index=[0]))[Out]:    age name0   1   nike
原创粉丝点击