python 学习语法之pandas添加行

来源:互联网 发布:世界各地社交软件 编辑:程序博客网 时间:2024/06/05 14:12
pandas打开csv文件,添加一行没有直接插入行的方法,只能将csv文件上下分割,然后拼接创建一个DataFrame准备插入csvdata中第2行与第3行之间,将csvdata分割为上下两段,利用append方法或者concat将它们拼接起来,注意参数ignore_index=True,新加的索引会重新排列,不设置为True则不会重新排列。first.append(insertRow,ignore_index=True).append(second,ignore_index=True)
或者pd.concat([first,insert,secondw],ignore_index=True)eg.
insertRow = pd.DataFrame([[0.,20.,3.,4.]],columns=['date','temperature','wind','humidity'])
above = table.loc[:2]
below = table.loc[3:]
newdata = up.append(insertRow,ignore_index=True).append(down,ignore_index=True)
或者
newdata2=pd.concat([up,insert,down],ignore_index=True)
再具体添加行作为标题实例
import pandas as pdimport csvRF_PATH = 'datapath/1.csv'titile = ["time0","time1","time2"]R2G = pd.read_csv(RF_PATH, header = None)insertRow = pd.DataFrame([titile])#R2G = pd.concat([instertRow, R2G], ignore_index = True)R2G = insertRow.append(R2G,ignore_index=True)df = R2G.to_csv('datapath/1-titile.csv', header = None, index = None)
#header和index设为None就会让DataFrame中的行列索引不出现在文件中
添加之前的数据为

添加之后的数据为

部分参考另一篇文章,其中还包括如何插入列
原创粉丝点击