我撰寫了此代碼來讀取 csv 檔案:
for file_to_open in filename:
file_path = os.path.realpath(file_to_open)
path_corrected = file_path.replace("file_mngt", "data")
opened = open(path_corrected)
reader = csv.reader(opened, delimiter = ";")
header = next(reader)
for row in reader:
print(row)
結果是(對于每一行)是這樣的:
['8', 'Thorgal', '8,49', '3', '25,47']
我想將每一行中的每個逗號都轉換為一個點。我在互聯網上查看,但他們都說我必須在 csv.reader 中放入“decimal = ','”,但它不起作用。請幫忙。謝謝。
uj5u.com熱心網友回復:
使用串列理解并呼叫串列的replace()每個元素。
print([item.replace(',', '.') for item in row])
uj5u.com熱心網友回復:
如果您打算進一步處理資料,則可以使用 pandas:
import pandas as pd
df = pd.read_csv("your/file/path", delimiter=";", decimal=",")
uj5u.com熱心網友回復:
我只會使用pandas圖書館。它支持處理 csv 檔案的所有基本功能,這使它變得更加容易。
你可以這樣做:
import pandas as pd
# read file with comma (,) as decimal separator
df = pd.read_csv(file_to_open, sep=";", decimal=",")
# write to file with dot (.) as decimal separator
df.to_csv("new_output_file.csv", sep=";", decimal=".", index=False)
afaik 默認的csv.reader不支持逗號小數,僅點/點。您必須添加自己的自定義map或轉換功能。
uj5u.com熱心網友回復:
看看convtools庫,它提供了大量的資料處理原語,并在幕后生成臨時代碼:
from convtools import conversion as c
from convtools.contrib.tables import Table
# e.g. without header, returns iterable of lists
rows = (
Table.from_csv(path_corrected, dialect=Table.csv_dialect(delimiter=";"))
# here we apply replace to every table cell
.update_all(c.this().call_method("replace", ",", "."))
.into_iter_rows(list)
)
# with header, returns iterable of dicts
rows = (
Table.from_csv(
path_corrected, header=True, dialect=Table.csv_dialect(delimiter=";")
)
.update_all(c.this().call_method("replace", ",", "."))
.into_iter_rows(dict)
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/359257.html
上一篇:如何從檔案創建多個資料幀?
