简体   繁体   English

将列数据分成csv文件中的两个新列

[英]separating column data into two new columns in a csv file

Good day all, 大家好

I am writing into a csv file and I need to separate one column's information into two new columns for example from this: 我正在写入一个csv文件,我需要将一个列的信息分成两个新列,例如:

Call
Goku (1000)

To have something that looks like this: 要具有以下内容:

Name  Landline
Goku  1000

so I need help on removing the brackets around the number and only taking the numbers inside it while renaming the Call column heading to Name and then create new column called Landline before writing the other columns, Name and Landline need to be the first two columns then the others follow. 因此,我需要删除数字上的方括号并仅取其中的数字,同时将“呼叫”列标题重命名为“名称”,然后在编写其他列之前创建一个名为“座机”的新列,“名称”和“座机”必须是前两列,然后其他人跟随。

I have the following code: 我有以下代码:

infile = "path to file"
outfile = "path to file"
def csv_wr():
# Opens output file for writing data into.
of = open(outfile, 'w')

# Reads the data from input file
with open(infile, 'r') as f:
    data = csv.DictReader(f)

    count = 0

    # Writing data into output file.
    for row in data:

        # Converts the date column.
        mydate = datetime.strptime(row['date'], '%d %b %Y %H:%M: %S').strftime('%Y-%m-%d %H:%M:%S')


        x = ''.join(row['value'])

        # Inserting '0' value to empty columns.
        if len(x) < 1:
            value = 0
        else:
            value = row['value']

            # If statement inserting data with commas except for the last row into the output file.
            if count > 0:
                textline = ",\n('{0}','{1}','{2}','{3}','{4}','{5}','{6}')".format(row['call'], row['to'], mydate,
                                                                                   row['duration'], row['bill'],
                                                                                   value, row['status'])

            else:
                textline = "('{0}','{1}','{2}','{3}','{4}','{5}','{6}')".format(row['call'], row['to'], mydate,
                                                                                row['duration'], row['bill'],
                                                                                value, row['status'])
of.write(textline)      

It would be best to make use of a csv.DictWriter() to create your CSV file. 最好利用csv.DictWriter()创建CSV文件。 The call field could be split using a regular expression to get the name and landline parts. 可以使用正则表达式拆分call字段,以获取namelandline部分。 This can then be added to the dictionary and written using the .writerow() call: 然后可以将其添加到字典中,并使用.writerow()调用来编写:

from collections import defaultdict
from datetime import datetime
import csv
import re

in_file = 'input.csv'
out_file = 'output.csv'
fieldnames = ['date', 'name', 'landline', 'to', 'duration', 'bill', 'status']

with open(in_file, 'r', newline='') as f_input, open(out_file, 'w', newline='') as f_output:
    csv_input = csv.DictReader(f_input)
    csv_output = csv.DictWriter(f_output, fieldnames=fieldnames, extrasaction='ignore')
    csv_output.writeheader()

    for row in csv_input:
        name, landline = re.match(r'(.*?) \((.*?)\)', row['call']).groups()
        row['name'] = name
        row['landline'] = landline
        row['date'] = datetime.strptime(row['date'], '%d %b %Y %H:%M: %S').strftime('%Y-%m-%d %H:%M:%S')
        csv_output.writerow(row)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将 csv 文件中的两列数据一起添加到 python 中同一 csv 文件中的新列中 - Adding two columns of data together from a csv file into a new column in the same csv file in python 将单列CSV数据转换为具有多列的新CSV文件 - Turning a single column of csv data into a new csv file with multiple columns 根据两列匹配来自两个csv文件的数据,并使用选定的列创建一个新的csv文件 - Matching data from two csv files based on two columns and creating a new csv file with selected columns 连接两列并存储在 csv 的新列中 - concat two columns and store in a new column in a csv 如何使用数据帧在新列中拆分两个 CSV 文件列,显示 pandas 中的匹配项? - How to split up two CSV file columns in a new column, showing matches in pandas, using dataframes? Numpy将CSV分为几列 - Numpy Separating CSV into columns 在python中分隔CSV列 - separating columns CSV in python 如何在.csv文件中分离数据? - How to go about separating data in a .csv file? 如何使用Pandas在CSV文件中创建新列,并根据这些列中的值添加数据 - How do I create a new column in a csv file using Pandas, and add data depending on the values in those columns 使用python和pandas将时间戳列拆分为CSV中的两个新列 - Split timestamp column into two new columns in CSV using python and pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM