我正在嘗試閱讀 excel 檔案中的所有內容,如下所示:

當我們讀取excel檔案時
xls = pd.ExcelFile('media/No2.xls')
我們在第 2 列中遇到了問題。而不是讓我們:
code
444444444505
444444444506
444444444506
777777777001
000000000025
000000000029
000000000044
000000000045
code
111111111111
111111111127
000000001341
它給了我們下一個:
code
444444444505
444444444506
444444444506
777777777001
25
29
44
45
code
111111111111
111111111127
1341
我們需要它000000001341保持為000000001341,而不是1341(以及其他在 em 前面帶有 0 的數字)。為了解決這個問題,我們嘗試了,好吧,我們能找到的一切!
dtype='str'\ str \ 'string' \ object \ 'object' \ whatever
converters={"2": object\string}, converters = object\string.
到底?沒有變化。它仍然讀取000000001341為整數并將其輸出為1341.
uj5u.com熱心網友回復:
好的。事實證明,根據您提供的檔案,檔案中看起來像字串的值實際上只是整數。它們看起來像字串,因為它們具有“特殊”格式。例如:

但如果我們應用格式“General”,我們會看到它只是一個數字:

這就是為什么 likexls = pd.read_excel('media/No2.xls', converters={2:str})沒有效果的原因,即使它應用于正確的列索引。
我已經轉向xlrd不同的解決方案。加載作業簿時,您可以通過xlrd添加來跟蹤作業表中單元格的數字格式。formatting_info=True基本上,下面的代碼遍歷第一張表中的所有行和列(假設這是正確的)并檢索每個單元格的數字格式。
例如,對于上圖中顯示的單元格(“1341”,格式為“00000001341”),回傳值將是“00000000000”。對于這種型別的所有潛在格式(“0”、“00”等),我們檢查是否xls.iloc[row,col]包含整數。如果是這樣,我們將整數更改為字串,并根據需要通過覆寫來添加所需的前導xls.iloc[row,col]零str(xls.iloc[row,col]).zfill(len(format_str))。我為將要更改的單元格添加了列印陳述句,以便您可以在控制臺中跟蹤所有更改是否有意義。
代碼如下。如果您仍然遇到任何困難,請告訴我。
import pandas as pd
# import xls, first sheet with header == None
xls = pd.read_excel('media/No2.xls', header=None)
import xlrd
# add formatting_info=True to allow for retrieving number format
book = xlrd.open_workbook('media/No2.xls', formatting_info=True)
sh = book.sheet_by_index(0)
# xlrd uses 0-index for rows, cols, e.g.: sh.cell(0,0) == A1
# from the mock data I collected the following unique formats.
# I'm assuming we only need to deal with the long strings of zeros
# the code below takes into account the possibility that the real data
# has more of these variants
# =============================================================================
# formats = ['0',
# '0000000', # this one
# '0" "',
# '00000000000', # this one
# '#,##0.00',
# '0.000',
# '0000000000', # this one
# '0.00',
# 'General']
# =============================================================================
# iterate over all rows (get length from xls DataFrame)
for row in range(xls.shape[0]):
# iterate over all cols (get length from xls DataFrame)
for col in range(xls.shape[1]):
# get format cell
cell = sh.cell(row,col)
xf_index = cell.xf_index
xf = book.xf_list[xf_index]
format_key = xf.format_key
format = book.format_map[format_key]
format_str = format.format_str
# if format like "0", "00", etc. and corresponding value in xls is an integer, define new string
if len(format_str) == format_str.count('0') and isinstance(xls.iloc[row, col],int):
temp = str(xls.iloc[row,col]).zfill(len(format_str))
# if new string (== temp) is same as the one already in xls, do nothing
# else: overwrite value
if str(xls.iloc[row,col]) != temp:
print(f'r{row} format: {format_str}; \timport: {xls.iloc[row,col]};'
f'\tchanged to: {str(xls.iloc[row,col]).zfill(len(format_str))}')
xls.iloc[row,col] = str(xls.iloc[row,col]).zfill(len(format_str))
uj5u.com熱心網友回復:
嘗試:
xls = pd.read_excel('media/No2.xls', converters={'code':str})
或者:
xls = pd.read_excel('media/No2.xls', converters={2:str})
默認情況下pd.read_excel將使用作業表中的第一行作為 DataFrame 的列名。因此,要設定轉換,您需要通過名稱('code')或索引(2,但沒有 qoutes!)參考正確的列。
uj5u.com熱心網友回復:
一種選擇是將資料作為單獨的行讀取,根據您的規范操作資料以獲得調整后的值。這是一種方法;我相信你可以進一步優化它。我將使用pyjanitor中的xlsx_cells來讀取資料:
# pip install pyjanitor
import pandas as pd
import janitor
content = jn.xlsx_cells('Downloads/TestDocument.xlsx', include_blank_cells=False)
numbers = content.loc[content.number_format.ne('General') & content.data_type.eq('n')]
In [65]: numbers
Out[65]:
value internal_value coordinate row column data_type is_date number_format
38 1 1 B24 24 2 n False 0
39 2 2 C24 24 3 n False 0
40 3 3 G24 24 7 n False 0
41 9 9 T24 24 20 n False 0
42 10 10 W24 24 23 n False 0
43 11 11 Y24 24 25 n False 0
44 12 12 AB24 24 28 n False 0
45 13 13 AG24 24 33 n False 0
46 14 14 AI24 24 35 n False 0
47 15 15 AL24 24 38 n False 0
48 1 1 B25 25 2 n False 0
49 2 2 B26 26 2 n False 0
51 1341 1341 G26 26 7 n False 00000000000
52 6 6 W26 26 23 n False 0.000
53 81.9 81.9 Y26 26 25 n False 0.00
54 491.4 491.4 AL26 26 38 n False 0.00
55 3 3 B27 27 2 n False 0
56 4 4 B28 28 2 n False 0
57 5 5 B29 29 2 n False 0
58 6 6 B30 30 2 n False 0
60 3005 3005 G30 30 7 n False 00000000000
61 12 12 W30 30 23 n False 0.000
62 59.4 59.4 Y30 30 25 n False 0.00
63 712.8 712.8 AL30 30 38 n False 0.00
64 7 7 B31 31 2 n False 0
65 10 10 B34 34 2 n False 0
66 11 11 B35 35 2 n False 0
67 12 12 B36 36 2 n False 0
68 13 13 B37 37 2 n False 0
number_format 為我們提供了我們所需要的;讓我們調整一下我們的優勢:
condition = numbers.number_format.str.contains('.', regex = False)
decimals = np.where(condition,
numbers
.number_format
.str.split('\.')
.str[-1]
.str
.len(),
0)
lengths = numbers.value.astype(str).str.len()
if_no_decimals = [x[:-z] str(y)
for x, y, z
in zip(numbers.number_format, numbers.value, lengths)]
decimals = [f"{x:.{y}f}"
for x, y
in zip(numbers.value, decimals)]
new_values = np.select([~condition, condition],
[if_no_decimals, decimals],
0)
numbers.assign(new_values = new_values)
value internal_value coordinate row column data_type is_date number_format new_values
38 1 1 B24 24 2 n False 0 1
39 2 2 C24 24 3 n False 0 2
40 3 3 G24 24 7 n False 0 3
41 9 9 T24 24 20 n False 0 9
42 10 10 W24 24 23 n False 0 10
43 11 11 Y24 24 25 n False 0 11
44 12 12 AB24 24 28 n False 0 12
45 13 13 AG24 24 33 n False 0 13
46 14 14 AI24 24 35 n False 0 14
47 15 15 AL24 24 38 n False 0 15
48 1 1 B25 25 2 n False 0 1
49 2 2 B26 26 2 n False 0 2
51 1341 1341 G26 26 7 n False 00000000000 00000001341
52 6 6 W26 26 23 n False 0.000 6.000
53 81.9 81.9 Y26 26 25 n False 0.00 81.90
54 491.4 491.4 AL26 26 38 n False 0.00 491.40
55 3 3 B27 27 2 n False 0 3
56 4 4 B28 28 2 n False 0 4
57 5 5 B29 29 2 n False 0 5
58 6 6 B30 30 2 n False 0 6
60 3005 3005 G30 30 7 n False 00000000000 00000003005
61 12 12 W30 30 23 n False 0.000 12.000
62 59.4 59.4 Y30 30 25 n False 0.00 59.40
63 712.8 712.8 AL30 30 38 n False 0.00 712.80
64 7 7 B31 31 2 n False 0 7
65 10 10 B34 34 2 n False 0 10
66 11 11 B35 35 2 n False 0 11
67 12 12 B36 36 2 n False 0 12
68 13 13 B37 37 2 n False 0 13
簡而言之,修改或修改列的邏輯,你最清楚。希望這能讓你朝著正確的方向前進。在xlsx_cells后臺使用 openpyxl 來獲取資料,并且僅適用于xlsx檔案 - 我必須將共享資料從 xls 轉換為 xlsx。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/489362.html
