pandas.DataFrame.append

方法

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  B
0  1  2
1  3  4
[In]:df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB'))
[In]:df.append(df2)
[Out]:
   A  B
0  1  2
1  3  4
0  5  6
1  7  8

ignore_index=True

[In]:df.append(df2, ignore_index=True)
[Out]:
   A  B
0  1  2
1  3  4
2  5  6
3  7  8

添加常数报错处理方法

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

import pandas as pd
df = 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 mrecords

E:\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 name
0   1   nike

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

[In]:df.append(pd.DataFrame({
    "name": "nike",
    "age": "1"   
},index=[0]))
[Out]:
    age name
0   1   nike
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值