ITPub博客

首页 > IT职业 > IT图书 > python怎么在数组中添加一行数据?

python怎么在数组中添加一行数据?

IT图书 作者:cxie72 时间:2021-09-11 10:15:56 0 删除 编辑

python在数组中添加一行数据的方法:

1、直接插入一行:

import pandas as pd
from pandas import DataFrame
 
df3=DataFrame(np.arange(16).reshape((4,4)),index=['a','b','c','d'],columns=['one','two','three','four']) 
 
# 新插入的行一定要加 index,不然会报错
df3.loc['new'] = ['a','a','a','a']
 
# 运行结果为
 
	one	two	three	four
a	0	1	2	3
b	4	5	6	7
c	8	9	10	11
d	12	13	14	15
new	a	a	a	a

2、新建一个同样的 dataframe, 然后合并两个dataframe

df4 = pd.DataFrame([6,6,6,6]).T
# 修改df4的column和df3的一致
df4.columns = df3.columns
# 把两个dataframe合并,需要设置 ignore_index=True
df_new = pd.concat([df3,df4],ignore_index=True)
 
# 运行结果
 
	one	two	three	four
0	0	1	2	3
1	4	5	6	7
2	8	9	10	11
3	12	13	14	15
4	a	a	a	a
5	6	6	6	6

更多Python知识请关注Python自学网。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1591/viewspace-2833503/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-15

  • 博文量
    91
  • 访问量
    808