简体   繁体   English

如何使用熊猫或普通python覆盖csv文件的特定列?

[英]How to overwrite a particular column of a csv file using pandas or normal python?

I am new to python. 我是python的新手。 I have a .csv file which has 13 columns. 我有一个具有13列的.csv文件。 I want to round off the floating values of the 2nd column which I was able to achieve successfully. 我想四舍五入到第二列的浮动值,这是我能够成功实现的。 I did this and stored it in a list. 我这样做,并将其存储在列表中。 Now I am unable to figure out how to overwrite the rounded off values into the same csv file and into the same column ie column 2? 现在,我无法弄清楚如何将四舍五入的值覆盖到同一csv文件和同一列(即列2)中? I am using python3. 我正在使用python3。 Any help will be much appreciated. 任何帮助都感激不尽。

My code is as follows: 我的代码如下:

Import statements for module import: 模块导入的导入语句:

import csv

Creating an empty list: 创建一个空列表:

list_string = []

Reading a csv file 读取CSV文件

with open('/home/user/Desktop/wine.csv', 'r') as csvDataFile:

    csvReader = csv.reader(csvDataFile, delimiter = ',')
    next(csvReader, None)                              
    for row in csvReader:
        floatParse = float(row[1])               
        closestInteger = int(round(floatParse))
        stringConvert = str(closestInteger)
        list_string.append(stringConvert)
print(list_string)

Writing into the same csv file for the second column (Overwrites the entire Excel file) 写入第二列的同一csv文件(覆盖整个Excel文件)

with open('/home/user/Desktop/wine.csv', 'w') as csvDataFile:

    writer = csv.writer(csvDataFile)
    next(csvDataFile)
    row[1] = list_string
    writer.writerows(row[1])

PS: The writing into the csv overwrites the entire csv and removes all the other columns which I don't want. PS:写入csv会覆盖整个csv并删除我不需要的所有其他列。 I just want to overwrite the 2nd column with rounded off values and keep the rest of the data same. 我只想用舍入值覆盖第二列,并保持其余数据不变。

this might be what you're looking for. 这可能是您要寻找的。

import pandas as pd
import numpy as np
#Some sample data
data = {"Document_ID": [102994,51861,51879,38242,60880,76139,76139],
    "SecondColumnName":    [7.256,1.222,3.16547,4.145658,4.154656,6.12,17.1568],
   }
wine = pd.DataFrame(data)

#This is how you'd read in your data
#wine = pd.read_csv('/home/user/Desktop/wine.csv')

#Replace the SecondColumnName with the real name
wine["SecondColumnName"] = wine["SecondColumnName"].map('{:,.2f}'.format)

#This will overwrite the sheet, but it will have all the data as before
wine.to_csv(/home/user/Desktop/wine.csv')

Pandas is way easier than read csv...I'd recommended checking it out. 熊猫比阅读csv更容易...我建议您检查一下。

I think this better answers the specific question. 我认为这可以更好地回答特定问题。 The key to this is to define an input_file and an output_file during the with part. 关键是在with部分期间定义一个input_file和一个output_file

The StringIO part is just there for sample data in this example. 在此示例中,StringIO部分仅用于示例数据。 newline='' is for Python 3. Without it, blank lines between each row appears in the output. newline=''适用于Python3。没有它,输出中的每一行之间将出现空白行。 More info . 更多信息

import csv
from io import StringIO

s = '''A,B,C,D,E,F,G,H,I,J,K,L
1,4.4343,3,4,5,6,7,8,9,10,11
1,8.6775433,3,4,5,6,7,8,9,10,11
1,16.83389832,3,4,5,6,7,8,9,10,11
1,32.2711122,3,4,5,6,7,8,9,10,11
1,128.949483,3,4,5,6,7,8,9,10,11'''

list_string = []

with StringIO(s) as input_file, open('output_file.csv', 'w', newline='') as output_file:
  reader = csv.reader(input_file)
  next(reader, None)
  writer = csv.writer(output_file)
  for row in reader:
    floatParse = float(row[1]) + 1
    closestInteger = int(round(floatParse))
    stringConvert = str(closestInteger)
    row[1] = stringConvert
    writer.writerow(row)

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

相关问题 如何使用特定列使用python对csv文件中的数据进行排序 - how to sort data in csv file using python using particular column 使用Python csv模块覆盖csv文件中的特定列 - Overwrite a specific column in a csv file using Python csv module 如何覆盖Pandas中的.csv文件? - How to overwrite .csv file in Pandas? 如何使用其他csv文件覆盖csv文件中的列 - How to overwrite a column in a csv file using a different csv file 如何使用 pandas 在特定列中的 csv 文件中查找特定单词 - How to find a particular word in a csv file in a particular column with pandas Python:使用pandas从csv文件中提取特定列(包含特殊字符) - Python: Extract a particular column(containing special characters) from csv file using pandas 使用python覆盖csv文件中的第一列和最后一列 - Overwrite the first and last column in csv file using python 如何在没有 pandas 库的情况下删除 csv 文件中的特定列 - How to delete a particular column in csv file without pandas library 如何在包含特定“子字符串”的单列 CSV 文件中选择特定 ROW 并使用 python Pandas 添加到新列表中? - How do I select a particular ROW in a single column CSV file containing a particular "substring" and add to a new list with python Pandas? 使用python将csv文件中的特定列附加到另一列 - append a particular column from a csv file to another using python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM