简体   繁体   English

如何为数组的所有元素添加前导零?

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

I am have a numpy array:我有一个 numpy 数组:

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

I wish to add a specific number of leading zeros to every element of this array so that the array looks like this:我希望为此数组的每个元素添加特定数量的前导零,以便数组如下所示:

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

What is the most efficient and fast way of doing this?这样做的最有效和最快速的方法是什么?

It's impossible to do this.这是不可能的。 The Python interpreter automatically converts numbers like 0004 to 4 . Python 解释器会自动将0004数字转换为4

The only way to do this is by converting everything to a string.做到这一点的唯一方法是将所有内容都转换为字符串。 If you want to do maths with the content of your array you convert it back to float.如果您想对数组的内容进行数学运算,请将其转换回浮点数。

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)


Output:输出:

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

Edit: However, if you have to use this array a lot, the most elegant way to achieve this is to make a class in my opinion.编辑:但是,如果您必须大量使用此数组,那么在我看来,实现此目的最优雅的方法是创建一个类。 That would feel more natural and you won't have to convert between strings and float each time.这会感觉更自然,您不必每次都在字符串和浮点数之间进行转换。 Thus being faster as well.因此也更快。

#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()


With one of the Python string formatting methods, we can create a simple function that pads a number to 7 places:使用 Python 字符串格式化方法之一,我们可以创建一个简单的函数,将数字填充到 7 位:

Display number with leading zeros 显示带前导零的数字

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

and use frompyfunc to apply that to all the elements of an array:并使用frompyfunc将其应用于数组的所有元素:

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

=== ===

You don't need frompyfunc if you are just writing this to a csv.如果您只是将其写入 csv,则不需要frompyfunc Just specify the desired fmt :只需指定所需的fmt

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

I'd recommend flattening your array to 1-dimension, applying the zfill() iteratively to each element in your newly-flattened list.我建议将数组展平为一维,将 zfill() 迭代应用于新展平列表中的每个元素。 This looks like这看起来像

# 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)

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