Csv python добавить колонку

Как добавить новый столбец в файл CSV?

Возможно ли, что в последнем столбце есть только «Ягода», потому что вы пишете «Ягода» только в файл? (строка + [‘Berry’]) Что вы ожидали написать?

@Dhara: я бы хотел, чтобы Berry использовался в качестве заголовка, а значение столбца Name — в качестве значения строки для Berry. Смотри выше.

7 ответов

Это должно дать вам представление о том, что делать:

>>> v = open('C:/test/test.csv') >>> r = csv.reader(v) >>> row0 = r.next() >>> row0.append('berry') >>> print row0 ['Name', 'Code', 'berry'] >>> for item in r: . item.append(item[0]) . print item . ['blackberry', '1', 'blackberry'] ['wineberry', '2', 'wineberry'] ['rasberry', '1', 'rasberry'] ['blueberry', '1', 'blueberry'] ['mulberry', '2', 'mulberry'] >>> 

Изменить, отметить в py3k, вы должны использовать next(r)

Спасибо, что приняли ответ. Здесь у вас есть бонус (ваш рабочий script):

import csv with open('C:/test/test.csv','r') as csvinput: with open('C:/test/output.csv', 'w') as csvoutput: writer = csv.writer(csvoutput, lineterminator='\n') reader = csv.reader(csvinput) all = [] row = next(reader) row.append('Berry') all.append(row) for row in reader: row.append(row[0]) all.append(row) writer.writerows(all) 
  • параметр lineterminator в csv.writer . По умолчанию это установлен на ‘\r\n’ , и поэтому у вас двойной интервал.
  • использование списка для добавления всех строк и их записи в один снимок с writerows . Если ваш файл очень, очень большой, это вероятно, это не очень хорошая идея (ОЗУ), но для нормальных файлов я думаю, что это быстрее, потому что меньше ввода/вывода.
  • Как указано в комментариях к этому сообщению, обратите внимание, что вместо вложенные два оператора with , вы можете сделать это в одной строке: с открытым (‘C:/test/test.csv’, ‘r’) как csvinput, open (‘C:/test/output.csv’, ‘w’) как csvoutput:
Читайте также:  Удалять или нет javascript

спасибо за примечание Я попытался, и это дает мне ошибку атрибута: у объекта «_csv.reader» нет атрибута «следующий». Есть ли у вас какие-либо идеи?

@Synetech Synthech, почему вы говорите, что файлы извлекаются из MSI? Я попытался извлечь с помощью 7zip, но файлов там нет.

Примечание: вместо вложения with операторами вы можете сделать это в той же строке, разделяя их запятой, например: with open(input_filename) as input_file, open(output_filename, ‘w’) as output_file

@Caumons Вы правы, и это было бы в настоящее время путь. Обратите внимание, что мой ответ пытался сохранить структуру кода OP, чтобы сосредоточиться на решении его проблемы.

Я удивлен, что никто не предложил Pandas. Хотя использование набора зависимостей типа Pandas может показаться более тяжелым, чем это необходимо для такой простой задачи, оно создает очень короткий script и Pandas — отличная библиотека для выполнения всех видов CSV (и действительно все типы данных) манипулирование данными. Не могу спорить с 4 строками кода:

import pandas as pd csv_input = pd.read_csv('input.csv') csv_input['Berries'] = csv_input['Name'] csv_input.to_csv('output.csv', index=False) 

Обратитесь Pandas Веб-сайт для получения дополнительной информации!

Name,Code,Berries blackberry,1,blackberry wineberry,2,wineberry rasberry,1,rasberry blueberry,1,blueberry mulberry,2,mulberry 
import csv with open('input.csv','r') as csvinput: with open('output.csv', 'w') as csvoutput: writer = csv.writer(csvoutput) for row in csv.reader(csvinput): if row[0] == "Name": writer.writerow(row+["Berry"]) else: writer.writerow(row+[row[0]]) 

Возможно, что-то вроде того, что вы намеревались?

Кроме того, csv обозначает значения, разделенные запятыми. Итак, вы вроде как запятые, чтобы отделить ваши ценности, как это, я думаю:

Name,Code blackberry,1 wineberry,2 rasberry,1 blueberry,1 mulberry,2 

Я использовал pandas, и он работал хорошо. Хотя я использовал его, мне пришлось открыть файл и добавить в него некоторые случайные столбцы, а затем сохранить обратно только в тот же файл.

Этот код добавляет несколько записей столбца, вы можете редактировать столько, сколько вам нужно.

import pandas as pd csv_input = pd.read_csv('testcase.csv') #reading my csv file csv_input['Phone1'] = csv_input['Name'] #this would also copy the cell value csv_input['Phone2'] = csv_input['Name'] csv_input['Phone3'] = csv_input['Name'] csv_input['Phone4'] = csv_input['Name'] csv_input['Phone5'] = csv_input['Name'] csv_input['Country'] = csv_input['Name'] csv_input['Website'] = csv_input['Name'] csv_input.to_csv('testcase.csv', index=False) #this writes back to your file 

Если вы хотите, чтобы значение ячейки не получало копию, прежде всего создайте пустой столбец в файле csv вручную, например, вы назвали его Часами то теперь для этого вы можете добавить эту строку в код выше,

csv_input['New Value'] = csv_input['Hours'] 

или просто мы можем, не добавляя ручную колонку, мы можем

csv_input['New Value'] = '' #simple and easy 

Надеюсь, что это поможет.

Источник

Add column to csv python – Python: Add a Column to an Existing CSV File

Python Add a Column to an Existing CSV File

Add column to csv python: In this article, we will discuss how to add a column to an existing CSV file using csv.reader and csv.DictWriter classes. Apart from appending the columns, we will also discuss how to insert columns in between other columns of the existing CSV file.

We also include these for beginners:

  • Add a list as a column to an existing csv file python
  • Add column from one csv to another python
  • Add column to existing csv
  • Add two columns in csv python
  • Add column to csv powershell
  • Python csv write to specific row and column
  • Add column to existing csv
  • Add two columns in csv python
  • Add column to csv powershell
  • Add a list as a column to an existing csv file python
  • Add column from one csv to another python
  • Python add a column to an existing csv file
  • Python add a new column to csv
  • Python add csv column to list
  • Python pandas append column to csv
  • Add a line to a csv file python

Original CSV file content

Method 1-Add a column with the same values to an existing CSV file

Python add column to csv: In this, we see how we make one column and add it to our CSV file but all the values in this column are the same.

Steps will be to append a column in CSV file are,

  1. Open ‘input.csv’ file in read mode and create csv.reader object for this CSV file
  2. Open ‘output.csv’ file in write mode and create csv.writer object for this CSV file
  3. Using reader object, read the ‘input.csv’ file line by line
  4. For each row (read like a list ), append default text in the list.
  5. Write this updated list / row in the ‘output.csv’ using csv.writer object for this file.
  6. Close both input.csv and output.csv file.

Let see this with the help of an example

from csv import writer from csv import reader default_text = 'New column' # Open the input_file in read mode and output_file in write mode with open('example1.csv', 'r') as read_obj, \ open('output_1.csv', 'w', newline='') as write_obj: # Create a csv.reader object from the input file object csv_reader = reader(read_obj) # Create a csv.writer object from the output file object csv_writer = writer(write_obj) # Read each row of the input csv file as list for row in csv_reader: # Append the default text in the row / list row.append(default_text) # Add the updated row / list to the output file csv_writer.writerow(row) output_data=pd.read_csv('output_1.csv') output_data.head()

Here we see that new column is added but all value in this column is same.

Now we see how we can add different values in the column.

Method 2-Add a column to an existing CSV file, based on values from other columns

How to add a new column to a csv file using python: In this method how we can make a new column but in this column the value we add will be a combination of two or more columns. As we know there is no direct function to achieve so we have to write our own function to achieve this task. Let see the code for this.

from csv import writer from csv import reader def add_column_in_csv(input_file, output_file, transform_row): """ Append a column in existing csv using csv.reader / csv.writer classes""" # Open the input_file in read mode and output_file in write mode with open(input_file, 'r') as read_obj, \ open(output_file, 'w', newline='') as write_obj: # Create a csv.reader object from the input file object csv_reader = reader(read_obj) # Create a csv.writer object from the output file object csv_writer = writer(write_obj) # Read each row of the input csv file as list for row in csv_reader: # Pass the list / row in the transform function to add column text for this row transform_row(row, csv_reader.line_num) # Write the updated row / list to the output file csv_writer.writerow(row) add_column_in_csv('example1.csv', 'output_2.csv', lambda row, line_num: row.append(row[0] + '__' + row[1])) output_data=pd.read_csv('output_2.csv') output_data.head()
total_bill tip sex smoker day time size total_bill__tip
0 16.99 1.01 Female No Sun Dinner 2 16.99__1.01
1 10.34 1.66 Male No Sun Dinner 3 10.34__1.66
2 21.01 3.50 Male No Sun Dinner 3 21.01__3.5
3 23.68 3.31 Male No Sun Dinner 2 23.68__3.31
4 24.59 3.61 Female No Sun Dinner 4 24.59__3.61

Here we see the new column is formed as the combination of the values of the 1st and 2nd column.

In the Lambda function, we received each row as a list and the line number. It then added a value in the list and the value is a merger of the first and second value of the list. It appended the column in the contents of example1.csv by merging values of the first and second columns and then saved the changes as output_2.csv files.

Method 3-Add a list as a column to an existing csv file

Python csv write column: In this method, we will add our own value in the column by making a list of our values and pass this into the function that we will make. Let see the code for this.

from csv import writer from csv import reader def add_column_in_csv(input_file, output_file, transform_row): """ Append a column in existing csv using csv.reader / csv.writer classes""" # Open the input_file in read mode and output_file in write mode with open(input_file, 'r') as read_obj, \ open(output_file, 'w', newline='') as write_obj: # Create a csv.reader object from the input file object csv_reader = reader(read_obj) # Create a csv.writer object from the output file object csv_writer = writer(write_obj) # Read each row of the input csv file as list for row in csv_reader: # Pass the list / row in the transform function to add column text for this row transform_row(row, csv_reader.line_num) # Write the updated row / list to the output file csv_writer.writerow(row) l=[] l.append("New Column") rows = len(data.axes[0]) for i in range(rows): val=i+1 l.append(val) add_column_in_csv('example1.csv', 'output_3.csv', lambda row, line_num: row.append(l[line_num - 1])) output_data=pd.read_csv('output_3.csv') output_data.head()
total_bill tip sex smoker day time size New Column
0 16.99 1.01 Female No Sun Dinner 2 1
1 10.34 1.66 Male No Sun Dinner 3 2
2 21.01 3.50 Male No Sun Dinner 3 3
3 23.68 3.31 Male No Sun Dinner 2 4
4 24.59 3.61 Female No Sun Dinner 4 5

In the Lambda function, we received each row as a list and the line number. It then added a value in the list and the value is an entry from our list l at index line_num – 1.Thus all the entries in the list l are added as a column in the CSV.

So these are some of the methods to add new column in csv.

Test yourself:

  1. Write to a specific column in csv python pandas?
  2. Write to specific column csv python?
  3. How do i add a column to an existing csv file in python?
  4. How to add column in existing csv file using python?

Источник

Оцените статью