Skip to main content
 首页 » 编程设计

python之在 Pandas 数据框中写入行并将其附加到现有数据框中

2024年12月31日11lyj

我的脚本输出为年份和该特定年份文章的字数:

abcd 
2013 
118 
2014 
23 
xyz 
2013 
1 
2014 
45 

我想将每一年作为一个新列添加到我现有的仅包含单词的数据框中。

预期输出:

Terms 2013  2014  2015  
abc   118   76    90 
xyz   23    0     36 

我的脚本的输入是一个 csv 文件:

Terms 
xyz 
abc 
efg 

我写的脚本是:

df = pd.read_csv('a.csv', header = None) 
 
for row in df.itertuples(): 
    term = (str(row[1])) 
    u = "http: term=%s&mindate=%d/01/01&maxdate=%d/12/31" 
    print(term) 
    startYear = 2013 
    endYear = 2018   
 
for year in range(startYear, endYear+1): 
    url = u % (term.replace(" ", "+"), year, year) 
    page = urllib.request.urlopen(url).read() 
    doc = ET.XML(page) 
    count = doc.find("Count").text 
    print(year) 
    print(count)  

df.head 是:

                         0 
0           1,2,3-triazole 
1  16s rrna gene amplicons 

任何帮助将不胜感激,提前致谢!!

请您参考如下方法:

我会用数组中的 numpy 读取 csv,然后用 numpy reshape 它,然后将生成的矩阵/二维数组转换为 DataFrame