[英]How to overwrite a particular column of a csv file using pandas or normal python?
我是python的新手。 我有一個具有13列的.csv文件。 我想四舍五入到第二列的浮動值,這是我能夠成功實現的。 我這樣做,並將其存儲在列表中。 現在,我無法弄清楚如何將四舍五入的值覆蓋到同一csv文件和同一列(即列2)中? 我正在使用python3。 任何幫助都感激不盡。
我的代碼如下:
模塊導入的導入語句:
import csv
創建一個空列表:
list_string = []
讀取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)
寫入第二列的同一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:寫入csv會覆蓋整個csv並刪除我不需要的所有其他列。 我只想用舍入值覆蓋第二列,並保持其余數據不變。
這可能是您要尋找的。
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')
熊貓比閱讀csv更容易...我建議您檢查一下。
我認為這可以更好地回答特定問題。 關鍵是在with
部分期間定義一個input_file
和一個output_file
。
在此示例中,StringIO部分僅用於示例數據。 newline=''
適用於Python3。沒有它,輸出中的每一行之間將出現空白行。 更多信息 。
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.