0

When I tried to read data from excel file (excell sheet screenshot attached), I get values as strings. But i need python datatype when i read excel file data.

#read excel file
dataframe1 = pd.read_excel('Data.xlsx')

Below code line give me list of string that makes sense.

#read mega_links column 
mega_linkss = dataframe1.iloc[:,7].tolist()
for link in mega_linkss:
    print(link, '   ',type(link))
    break

OUTPUT:

"['https://mega.nz/folder/KXICCZrS#dJT2bqTh3eK_xbbMPuNglQ']"     <class 'str'>
As you can see class is 'str'

To get class as 'list', i tried following code.

# when i used list function to convert string in list. 
for link in mega_linkss:
    print(list(link))
    break

OUTPUT:

['[', "'", 'h', 't', 't', 'p', 's', ':', '/', '/', 'm', 'e', 'g', 'a', '.', 'n', 'z', '/', 'f', 'o', 'l', 'd', 'e', 'r', '/', 'K', 'X', 'I', 'C', 'C', 'Z', 'r', 'S', '#', 'd', 'J', 'T', '2', 'b', 'q', 'T', 'h', '3', 'e', 'K', '_', 'x', 'b', 'b', 'M', 'P', 'u', 'N', 'g', 'l', 'Q', "'", ']']

I need output like this.

OUTPUT:

['https://mega.nz/folder/KXICCZrS#dJT2bqTh3eK_xbbMPuNglQ']     <class 'list'>

Excell Sheet Screenshot is attached.

Code Screenshot is attached for a better understanding of what I need.

Thanks

[enter image description here](https://i.stack.imgur.com/yLsK8.jpg)

I need output like this.

OUTPUT:

['https://mega.nz/folder/KXICCZrS#dJT2bqTh3eK_xbbMPuNglQ']     <class 'list'>
Awan
  • 1
  • 1
  • 1
    Does this answer your question? [How to convert string representation of list to a list](https://stackoverflow.com/questions/1894269/how-to-convert-string-representation-of-list-to-a-list) – fsimonjetz Feb 18 '23 at 10:59

1 Answers1

1

The value in your excel file is a string "['https...']". It is a string representation of a list, so if you wanted to convert it to a list, you could use eval(string) or ast.literal_eval(string).

eval is considered unsafe, and ast.literal_eval is a safer alternative, part of a built-in ast module.

For example, ast.literal_eval("[1,2,3]") = [1, 2, 3]. Likewise, ast.literal_eval(link) will return a list version of your link, which according to your excel table will be a list with a single string in it.

stunlocked
  • 181
  • 10