python 将行转换为数组

n9vozmp4  于 2023-03-06  发布在  Python
关注(0)|答案(2)|浏览(188)

我想将所有行转换为数组。例如,我有多个值,这些值存储在CSV中。假设A1中的位置值为Message B1中的位置值为Field=1234 C1中的位置值为Field=0023
比如从A1到AZ1左右,我有数据行。
所以我想把它转换成数组,然后按不同的数据字段存储在postgres中。

在我的csv中没有任何列名。

我期待这方面的python代码。之后,我想只捕捉特定的数据字段值创建列名。

bf1o4zei

bf1o4zei1#

import csv 
with open("file.csv") as file:
    # generator 
    reader = csv.reader(file)
    for row in reader:
         # this will print each row as a list/array
         print(row)
b09cbbtk

b09cbbtk2#

你可以用Pandas来做这个。例如

# importing the module
import pandas as pd
  
# creating a DataFrame
data = {'Name' : ['Sana', 'Manaan', 'Rizwan', 
                 'Uman', 'Usama'],  
        'Computer' : [8, 5, 6, 9, 7],  
        'Farsi' : [7, 9, 5, 4, 7], 
        'Urdu' : [7, 4, 7, 6, 8]} 
df = pd.DataFrame(data)
print("Original DataFrame")
display(df)
  
print("Value of row 3 (Uman)")
display(df.iloc[3]) # Getting the row using iloc

array = []

for i in df.iloc[3]:
  array.append(i)

display(array)

首先,你可以从csv中读取数据。在上面的例子中,我只是创建了一个简单的DataFrame。然后使用iloc方法选择特定的行。然后将其添加到数组中。记住,索引从0开始,所以3表示第4行。Output

相关问题