python如何提取csv文件某一列的第一个字符,Python:根据第一列的第一个字符拆分CSV文件...

本文介绍了一种高效的方法,利用Pandas库根据CSV文件第一列的第一个字符来拆分大型CSV文件。通过读取文件,然后使用groupby函数结合字符串切片操作,将数据分割并保存为多个以首字母命名的子文件。
摘要由CSDN通过智能技术生成

I have a series of large CSV files "basename.csv" like:

B1,3,5,6

B2,2,1,5

B3,1,9,0

C1,4,7,9

C2,1,9,3

C3,8,5,2

I would like to split them into different files like:

basename_B.csv

B1,3,5,6

B2,2,1,5

B3,1,9,0

basename_C.csv

C1,4,7,9

C2,1,9,3

C3,8,5,2

I have already done similar things in the past with for loops and ifs, but I was wondering if there is a more efficient way of doing this with Pandas or whatever.

SOLUTION

Adapting the solution from @chthonicdaemon and @jezrael, I came up with this:

def split_csv():

for dfile in glob.glob('*.csv'):

df = pd.read_csv(dfile, header=None)

for letter, group in df.groupby(df[0].str[0]):

group.to_csv((os.path.splitext(dfile)[0]) +

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值