简体   繁体   中英

How to make 2 dimensiion array in python with document data

I want to make a two-dimensional array with string values from my data document csv, but I have trouble with Indexes

my data =

1.alquran,tunjuk,taqwa,perintah,larang,manfaat  2.taqwa,ghaib,allah,malaikat,surga,neraka,rasul,iman,ibadah,manfaat,taat,ridha
3.taqwa,alquran,hadist,kitab,allah,akhirat,ciri

in a document csv

def ubah(kata):
    a=[]
    for i in range (0,19):
        a.append([kata.values[i,j] for j in range (0,13)])
    return a

and the wanted result is

[['alquran','tunjuk','taqwa','perintah','larang','manfaat'],<br>['taqwa','ghaib','allah','malaikat','surga','neraka','rasul','iman','ibadah','manfaat','taat','ridha'],<br>['taqwa','alquran','hadist','kitab','allah','akhirat','ciri']]

Please remove values[i,j] from the for loop and replace it with j .

for i in range (0,19): 
    a.append([kata[j] for j in range (0,3)]) 

You can modify your function as:

def ubah(kata):
    a = []
    line = kata.split("\n") # will create an array of rows
    for i in range(len(line)):
        a.append(line[i].split(",")) # will add the separated values
    return a

df = open("data.csv", 'r')
kata = df.read()
dataarray = ubah(kata) # calling the function
print(dataarray)

The above program gives the result as you want, like

[['alquran', 'tunjuk', 'taqwa', 'perintah', 'larang', 'manfaat'], ['taqwa', 'ghaib', 'allah', 'malaikat', 'surga', 'neraka', 'rasul', 'iman', 'ibadah', 'manfaat', 'taat', 'ridha '], ['taqwa', 'alquran', 'hadist', 'kitab', 'allah', 'akhirat', 'ciri']]

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM