簡體   English   中英

如何為數組的所有元素添加前導零?

[英]How to add leading zeros to all elements of an array?

我有一個 numpy 數組:

   [[4907., 4907., 4907., ..., 4907., 4907., 4907.],
   [4907., 4907., 4907., ..., 4907., 4907., 4907.],
   [4907., 4907., 4907., ..., 4907., 4907., 4907.]]

我希望為此數組的每個元素添加特定數量的前導零,以便數組如下所示:

  [[0004907., 0004907., 0004907., ..., 0004907., 0004907., 0004907.],
   [0004907., 0004907., 0004907., ..., 0004907., 0004907., 0004907.],
   [0004907., 0004907., 0004907., ..., 0004907., 0004907., 0004907.]]

這樣做的最有效和最快速的方法是什么?

這是不可能的。 Python 解釋器會自動將0004數字轉換為4

做到這一點的唯一方法是將所有內容都轉換為字符串。 如果您想對數組的內容進行數學運算,請將其轉換回浮點數。

arr = [
    [4907., 4907., 4907.],
    [4907., 4907., 4907.],
    [4907., 4907., 4907.]
]

new_arr = []

for i in range(0, len(arr)):
    new_arr.append([])
    for j in range(0, len(arr)):
        nr = arr[i][j]
        new_arr[i].append(str(nr).zfill(len(str(nr)) + 3))


print(new_arr)


輸出:

[['0004907.0', '0004907.0', '0004907.0'], ['0004907.0', '0004907.0', '0004907.0'], ['0004907.0', '0004907.0', '0004907.0']]

編輯:但是,如果您必須大量使用此數組,那么在我看來,實現此目的最優雅的方法是創建一個類。 這會感覺更自然,您不必每次都在字符串和浮點數之間進行轉換。 因此也更快。

#Special class
class SpecialArray:
    #Your array
    arr = [
        [4907., 4907., 4907.],
        [4907., 4907., 4907.],
        [4907., 4907., 4907.]
    ]


    #Append leading zero's when class is initiated
    def __init__(self):
        temp_arr = []

        for i in range(0, len(self.arr)):
            temp_arr.append([])
            for j in range(0, len(self.arr)):
                nr = self.arr[i][j]
                temp_arr[i].append(str(nr).zfill(len(str(nr)) + 3))

        self.arr = temp_arr

    #Print out array
    def print(self):
        print(self.arr)

    #Get a value to to math
    #If asString is true, you get back the string with leading zero's (not for math)
    def get(self, x, y, asString = False):
        if not asString:
            return float(self.arr[x][y])
        else:
            return self.arr[x][y]

    #TODO: Make function to append etc here

###Rest of your program
def main():
    #Initiate your array
    arr = SpecialArray()

    #Print out whole array
    arr.print()
    #Output:
    #[['0004907.0', '0004907.0', '0004907.0'], ['0004907.0', '0004907.0', '0004907.0'], ['0004907.0', '0004907.0', '0004907.0']]


    #Print out one element
    print(arr.get(1, 2, True))
    #Output:
    #0004907.0

    #Get one element and increase by one (do math)
    x = arr.get(1,2) + 1
    print(x)
    #Output:
    #4908.0

main()


使用 Python 字符串格式化方法之一,我們可以創建一個簡單的函數,將數字填充到 7 位:

顯示帶前導零的數字

def foo(num):
    return "{:07d}".format(num)
In [301]: arr = [[4907, 12],[1, 4907]]                                                         

並使用frompyfunc將其應用於數組的所有元素:

In [302]: np.frompyfunc(foo,1,1)(arr)                                                          
Out[302]: 
array([['0004907', '0000012'],
       ['0000001', '0004907']], dtype=object)

===

如果您只是將其寫入 csv,則不需要frompyfunc 只需指定所需的fmt

In [359]: np.savetxt('padded.txt', arr, fmt="%07d")                                            
In [360]: cat padded.txt                                                                       
0004907 0000012
0000001 0004907

我建議將數組展平為一維,將 zfill() 迭代應用於新展平列表中的每個元素。 這看起來像

# Initiate list
l = np.array([[1,1],[2,2],[3,3],[4,4]])

print(l)

# Specify length of output string you want
desired_pad = 2

# Create a numpy array version, flatten to 1-d
flat_l = np.array(l).flatten()

# Apply zfill to each element in flattened array, then reshape to initial shape
output = np.array([str(flat_l[i]).zfill(desired_pad) for i in np.arange(0,len(flat_l))]).reshape(l.shape)

print(output)

輸出

[[1 1]
 [2 2]
 [3 3]
 [4 4]]
[['01' '01']
 ['02' '02']
 ['03' '03']
 ['04' '04']]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM