gpt4 book ai didi

python - 如何从 CSV 移动表格的列?

转载 作者:行者123 更新时间:2023-11-28 19:18:20 24 4
gpt4 key购买 nike

我已经为 CSV 数据添加了新标题(参数),并且必须计算新参数,因此它需要保持为空。我需要将整个数据向右移动一列,但我不知道如何使用 python v 3.2谁能帮帮我?

所以当我用 excel 打开我的 python CSV 文件时,它给了我这样的东西( super 简化版本,我有成千上万的行和列)

P1 P2 P3 P4 P5 ...

1 2 3 4 5
1 2 3 4 5
1 2 3 4 5

..

我想将其更改为;将 P1 留空。

P1 P2 P3 P4 P5 ...

1 2 3 4
1 2 3 4
1 2 3 4

这是我目前得到的代码。我只想将该数据向右移动一列。有人可以帮我吗?提前致谢!

    import csv

# reads the input and spits out the output
with open ('DownloadDB_CSV1.csv', 'r') as csvinput:
with open ('outputCSV.csv', 'w', newline ='') as csvoutput:
reader = csv.reader(csvinput, delimiter = ',')
writer = csv.writer(csvoutput, delimiter = ',')
all = []
row = next(reader)
row.insert(0,'GenomePosition')
all.append(row)



for row in reader:
all.append(row)
contents = row[0::] # sepearte it to a variable
writer.writerows(all)

最佳答案

要插入一个空列,您唯一需要做的就是向每一行添加一个初始 ,。这是执行此操作的一些代码 - 您甚至不需要 CSV 模块即可执行此操作。根据您的示例,我想您不想移动标题,对吧?

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# test_csv.py
#
# Copyright 2015 John Coppens <john@jcoppens.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
#

SEPARATOR = ","

def add_empty(infile, outfile):
with open(outfile, "w") as outf:
with open(infile, "r") as inf:
line = inf.readline() # Copy the header
outf.write(line)

while True:
line = inf.readline()
if line == "": break # EOF
outf.write("" + SEPARATOR + line)

def main():
add_empty("test.csv", "testshifted.csv")
return 0

if __name__ == '__main__':
main()

关于python - 如何从 CSV 移动表格的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30676969/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com