Python pandas中DataFrame中增删行列

1. 概述

  • 添加行: df.loc[]以及df.append()两种方法
  • 添加列: df[]和df.insert()两种方法
  • 添加行列: concat()和reindex()两种方法
  • loc bug解决

2. 添加行

2.1. 采用loc[]方法

loc方法和iloc方法一样,可以索引DataFrame数据,一般是通过data.loc[index, col] = value

2.2. 采用append()方法

2.2.1. 采用append方法合并两个dataframe

2.2.2. 采用append方法添加多行

2.3. 采用concat()方法

拼接数据,好处是可以同时新增多个列名和行名

  • 输出结果

3. 添加列

3.1. 采用df[]

  • 输出结果

3.2. 采用insert()

  • 输出结果

3.3. 采用reindex()函数

  • 输出结果

  • Series的reindex用法

如果没有对应数值,需要取前一个索引的值填充,可用ffill方法实现

  • 输出结果

  • DataFrame的reindex方法: 区别主要在于,DataFrame可以对index或columns使用reindex方法。

4. 错误解决: Passing list-likes to .loc or [] with any missing labels

KeyError: "Passing list-likes to .loc or [] with any missing labels is no longer supported. The following labels were missing: Index(['b'], dtype='object').

5. 参考

赞赏

微信赞赏支付宝赞赏

发表评论

邮箱地址不会被公开。 必填项已用*标注