当前位置:首页 » 编程语言 » python合并csv

python合并csv

发布时间: 2022-06-08 04:07:21

python合并表格报错

你所定义的list node class和python自带的list type是不同的东西,不能通用,必须先转换
其他小错我直接帮你改掉了
下面是改好可以运行的代码:
class ListNode(object): def __init__(self,val): self.val = val self.next = None def __repr__(self): return str(self.val) def LinkedList(pythonlist): l = ListNode(pythonlist[0]) c = l for i in range(1,len(pythonlist)): l.next = ListNode(pythonlist[i]) l = l.next return c def PythonList(ListNode): l = [] while ListNode != None: l.append(ListNode.val) ListNode = ListNode.next return l class Solution(object): def mergeTwoLists(self,l1,l2): if l1 is None: return l2 if l2 is None: return l1 mmyhead=ListNode(0) mmyhead.next=None p=mmyhead while l1 is not None and l2 is not None: if l1.val<l2.val: p.next=l1 l1=l1.next else: p.next=l2 l2=l2.next p=p.next if l1 is not None: p.next=l1 else: p.next=l2 return mmyhead.next l1=LinkedList([1,3,5,7])l2=LinkedList([2,4,6,8])sol = Solution()print(PythonList(sol.mergeTwoLists(l1,l2)))

(LinkedList(pythonlist) 方法把一个传统的python list转换成你用的首位相衔的listnode 形式,PythonList(ListNode) 则是转换回来)
同时,linkedlist的数据类型在c里面比较常用,python里面一般用不着这么麻烦
希望对你有帮助

㈡ python csv模块问题请教

csv文件就是文本文件,你可以直接按格式写入.
但是用python自带的csv模块更方便,我也没怎么用过,你可以参考以下链接.

㈢ python中如何将多个csv文件合并成一个

import glob
import time

csvx_list = glob.glob('*.csv')
print('总共发现%s个CSV文件'% len(csvx_list))
time.sleep(2)
print('正在处理............')
for i in csvx_list:
fr = open(i,'r').read()
with open('csv_to_csv.csv','a') as f:
f.write(fr)
print('写入成功!')
print('写入完毕!')
print('10秒钟自动关闭程序!')
time.sleep(10)

㈣ Python 和 BeautifulSoup 怎么把 html table 处理成 csv

代码

#coding:utf8
importurllib
importurllib2
importcookielib
importre
importcsv
importcodecs
frombs4importBeautifulSoup

wiki='https://zh.wikipedia.org/wiki/%E6%96%87%E4%BB%B6%E7%BC%96%E8%BE%91%E5%99%A8%E6%AF%94%E8%BE%83'
header={'User-Agent':'Mozilla/5.0'}
req=urllib2.Request(wiki,headers=header)
page=urllib2.urlopen(req)
soup=BeautifulSoup(page)

name=""#名字
creater=""#归属
first=""#首次公开发布的时间
latest=""#最新稳定版本
cost=""#售价
licence=""#授权条款

table=soup.find("table",{"class":"sortablewikitable"})

f=open('table.csv','w')
csv_writer=csv.writer(f)

td_th=re.compile('t[dh]')

forrowintable.findAll("tr"):
cells=row.findAll(td_th)
iflen(cells)==6:
name=cells[0].find(text=True)
ifnotname:
continue
creater=cells[1].find(text=True)
first=cells[2].find(text=True)
latest=cells[3].find(text=True)
cost=cells[4].find(text=True)
licence=cells[5].find(text=True)

csv_writer.writerow([x.encode('utf-8')forxin[name,creater,first,latest,cost,licence]])

f.close()

㈤ PYTHON关于excel和csv转换

Python处理csv文件时经常会用到讲csv文件整体读取为一个数组或者矩阵的情况,借助numpy包,可以使用如下代码简洁高效低实现: [python] view plain import numpy my_matrix = numpy.loadtxt(open("c:\\1.csv","rb"),delimiter=",",skiprows=0) 将数组或者矩阵存储为csv文件可以使用如下代码实现: [python] view plain numpy.savetxt('new.csv', my_matrix, delimiter = ',')

㈥ python如何对数据的列进行规则式合并

首先导入列表中的数组,再对每一列进行检测若发现相同的数字就用0来填充,在按列求和,生成一个新的数组再合并到原来数组的下面,生成一个新的列表:

import pandas as pd
a=pd.readflie( "XXX.csv") //XXX.csv为你的列表生成的数组文件的路径
for i in a[i]: //循环找出重复的数据并以0替换
for j in a[i,j]:
if a[i,j]==a[i,j+1]

a[i,j+1]=0

for k in a[k,n]:
for n in a[k,n]:

a[k,n]+=a[k,n]

a[k,n+1]=a[k,n]/n //求平均值

这段代码复制到pycharn就可以直接运行了,打字不易,求理解

㈦ python实现excel合并

Created on Mon Mar 16 11:23:05 2015
@author: admin
"""
# 分批次运行,先得到books, 再运行,利用print 来debugimport pandas as pd
import numpy as np
import matplotlib as pl
import os
count=0
#ori_path='xx'
ori_path='C:\Python27\data\sample'
def get_xls_books(ori_path): # get target filename and dir of a pathtemp = list(os.walk(ori_path)) #tmp is list ,tmp[0]该目录文件路径和文件名, tmp[1]:子目录文件路径,文件名称book_path=[]
book_name=[]
root=temp[0][0]
for i in temp[0][2]:
if os.path.splitext(i)[1] == '.xlsx': #splite filenameobj_path=os.path.join(root,i)
book_path.append(obj_path)
book_name.append(os.path.splitext(i)[0])
return zip(book_path, book_name)
def get_xls_sheets(obj_path): #get all sheets of a object pathxls=pd.ExcelFile(obj_path)
sheet_names=xls.sheet_names
sheets=[xls.parse(i) for i in range(0,len(sheet_names)) ] # use parse can get dataframe saved into a listreturn zip(sheet_names,sheets)
books=get_xls_books(ori_path) # book paths list#xls=pd.ExcelFile(books[0])
#print xls.parse(0).columns
for book in books: # this loop get a bookbookname=book[1]
bookpath=book[0]
sheets=get_xls_sheets(bookpath) # get all sheets and names from book pathfor i in range(len(sheets)): #operate each sheet, is range(len) not lensheetname=sheets[i][0]
name=bookname+'-'+sheetname+'.'+'csv'
pd_sheet=sheets[i][1] # dataFrame
cols=pd_sheet.columns
pdf=pd_sheet[[cols[17],cols[18],cols[4],cols[6],cols[8],cols[10],cols[19],cols[16]]] # use emunerate functionpdf.columns=['area','patch','wangdian','operator','custid','servid','servtype','is_identify'] # renamepdf1=pdf[pdf['is_identify']=='是'] #filterpdf2=pdf1.drop('is_identify',1)
pdf2.to_csv(os.path.join(ori_path,name), header=None, index=None)

㈧ 怎么用python把一个*。csv 文件里面的数据整合成一个表格

假设你这里是一个大文件。用CSV缺省配置不能读大文件。我们自己写一个。

defreadfile(fn):
fp=open(fp,'rb')
whileTrue:
line=fp.readline()
ifnotline:break
line=line.strip()
yieldline.split(',')
fp.close()
importos,sys,time,glob
files=glob.glob("*.csv")
data={}
forfninfiles:
record_number=0
forcolsinreadline(fn):
ifrecord_number==0:
fornameincols:data[name]=[]
else:
forcincols:
data[name].append(c)
record_number+=1
#end

这样就把所有的文件都读到一个data变量里了,而且是按列存放的。

㈨ python对多个csv文件里提取指定列汇总到一个新生成的csv文件

#!/usr/bin/envpython
#coding:utf-8

importos
importre


defparserln(ln,patt):
"""用给定的正则表达式解析行"""
matched=patt.match(ln)
ifmatched:
returnmatched.groupdict()


defgetdata(filename,parser,callback=None):
"""用指定的解析方法parser解析指定文件,
用callback进行数据加工过的数据列表
"""
withopen(filename,'rt')ashandle:
returnmap(
callback,
filter(None,map(parser,handle))
)


defstorage(filename,dataserial,spliter=','):
"""将数据序列按行存储到指定文件,
每一序列元素间用指定的字符分割"""
withopen(filename,'wt')ashandle:
handle.writelines([
"%s "%(spliter.join(map(str,item)))
foritemindataserial
])


if__name__=="__main__":
patt=re.compile(
r"""^
(?P<month>d+),
(?P<amount>d+),
(?P<usage>d+)
s*$""",
re.I|re.U|re.X)
datapath='datasource'
#datasource下所有存在"usage.csv"文件的子目录
subpaths=[
os.path.join(datapath,path)
forpathinos.listdir(datapath)
if(os.path.isdir(os.path.join(datapath,path))
andos.path.exists(
os.path.join(datapath,path,"usage.txt"))
)
]
storage(
'store.csv',
zip(*map(
lambdapath:getdata(
os.path.join(path,"usage.csv"),
#解析方法为用patt解析行
parser=lambdaln:parserln(ln,patt),
#数据加工方法是取出"amount"转成整数
callback=lambdax:int(x["amount"]),
),
subpaths))
)

$ tail -n 12 datasource/*/*.csv
==> datasource/2014/usage.csv <==
1,4234,423
2,3523,432
3,4352,438
4,4792,458
5,4823,834
6,5093,734
7,4743,832
8,5152,859
9,4932,810
10,4993,802
11,4999,810
12,5052,850

==> datasource/2015/usage.csv <==
1,5234,423
2,4523,432
3,5352,438
4,5792,458
5,6823,834
6,6093,734
7,6743,832
8,7152,859
9,6932,810
10,6993,802
11,6999,810
12,7052,850
(venv)tim@crunchbang:~/workspace/$

$ cat store.csv
4234,5234
3523,4523
4352,5352
4792,5792
4823,6823
5093,6093
4743,6743
5152,7152
4932,6932
4993,6993
4999,6999
5052,7052
$

㈩ python 如何把多个文件内容合并到以一个文件

Python编程将多个文件合并,代码如下:

#例子:合并a.txt、b.txt、c.txt合并成d.txt文件

#文件列表,遍于读取

flist = ['a.txt','b.txt','c.txt']

#要写入的文件

ofile = open('d.txt', 'w')

#遍历读取所有文件,并写入到输出文件

for fr in flist:
for txt in open(fr, 'r'):
ofile.write(txt)
ofile.close()
效果如下:

热点内容
scratch少儿编程课程 发布:2025-04-16 17:11:44 浏览:637
荣耀x10从哪里设置密码 发布:2025-04-16 17:11:43 浏览:366
java从入门到精通视频 发布:2025-04-16 17:11:43 浏览:82
php微信接口教程 发布:2025-04-16 17:07:30 浏览:308
android实现阴影 发布:2025-04-16 16:50:08 浏览:789
粉笔直播课缓存 发布:2025-04-16 16:31:21 浏览:339
机顶盒都有什么配置 发布:2025-04-16 16:24:37 浏览:210
编写手游反编译都需要学习什么 发布:2025-04-16 16:19:36 浏览:810
proteus编译文件位置 发布:2025-04-16 16:18:44 浏览:364
土压缩的本质 发布:2025-04-16 16:13:21 浏览:590