pandas中的序列与表的合并

行追加数据

append()

使用场合:

需要在原数据的基础上,再次增加行数据

使用方法:

append(要增加上去的项目, ignore_index = True或False )
 ignore_index = 表示是否需要忽略行索引

代码实战:

import pandas as pd

df1 = pd.DataFrame({"Name":["张三", "李四", "张三"],
                    "age":[20, 30, 40],
                    "class":["one", "two", "three"]})
a = df1.append({"Name":"妍", "age":22, "class":"one"}, ignore_index=True)
print(df1)
print()
print(a)

运行结果:

  Name  age  class
0   张三   20    one
1   李四   30    two
2   张三   40  three

  Name  age  class
0   张三   20    one
1   李四   30    two
2   张三   40  three
322    one

由上可知:

pandas的DataFrame数据结构中的 .append() 方法是在行的基础之上追加数据的。
pandas中的 .append() 方法并没有改变原始的数据
python 中 列表的.append() 方法是将 列表值发生了变化,是在原列表的基础上做出的改动。

列追加类别

assign()

使用场合:

可以利用 .assign() 添加新的列
一般通过 df[‘new_col’] = … 的形式就可以等价地添加新列。

使用方法:

代码实战:

import pandas as pd

df1 = pd.DataFrame({"Name":["张三", "李四", "张三"],
                    "age":[20, 30, 40],
                    "class":["one", "two", "three"]})
s = pd.Series([98, 94, 90])
new = df1.assign(score=s)
print(df1)
print()
print(new)
print()
df1["score"] = s
print(df1)

运行代码:

  Name  age  class
0   张三   20    one
1   李四   30    two
2   张三   40  three

  Name  age  class  score
0   张三   20    one     98
1   李四   30    two     94
2   张三   40  three     90

  Name  age  class  score
0   张三   20    one     98
1   李四   30    two     94
2   张三   40  three     90

由此看出,同时,使用 [ ] 修改的缺点是它会直接在原表上进行改动,而 assign 返回的是一个临时副本。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值