4

Excel has a list of numbers, I am expecting to see something like this:

[110652450, 5309154]

However I see something like this:

[[110652450], [5309154]] 

I tried newtest = [x[:-1] for x in df] suggested on a similar question but that just removes my numbers and keeps the braquets

df = pd.read_excel(filename.xlsx",sheetname='Sheet1')


df = df.values.tolist()

print(df)
scharette
  • 9,437
  • 8
  • 33
  • 67
pepperjohn
  • 67
  • 1
  • 3
  • 11
  • You seem to think that `[[110652450], [5309154]] ` is a string but as far as I can see it's a multidimensional list. You have to access it by index. so `x[0]` would give you `[110652450], [5309154]` and `x[0][0]` will return `110652450`. – mas Jul 24 '18 at 13:47
  • I suggest reading up a bit more on how to work with lists and other data types in Python. – mas Jul 24 '18 at 13:48
  • @malan It doesn't seem that OP is trying to treat this list as a string (he even uses the word "list" in the title of the question). Where does he imply that `df` is a string? – Joel Jul 24 '18 at 13:50
  • @Joel, perhaps you're correct, but by accessing a slice of as though he was trimming off the brackets (though if he were doing that he would have written `x[1:-1]`) it just seemed to me, on an intuitive basis, that he was understanding the list of lists to be a string formatted with external brackets. – mas Jul 24 '18 at 13:55
  • @Joel, I believe my initial comment was even incorrect. `x[0]` would result in `[110652450]` as the list is a list of single item lists and not a list of two-item lists. – mas Jul 24 '18 at 13:57

5 Answers5

6

I didn't quite get your question, but you seem to be looking for something like this?

df = [[110652450], [5309154]]
newest = [i[0] for i in df]
print(newest)
>> [110652450,5309154]
Mr. T
  • 356
  • 3
  • 17
2

numpy.squeeze might be the preferred method to do this. Call np.squeeze(a) for the array that you wish to flatten. np.squeeze should be much faster than a list comprehension such as [e[0] for e in a]

swhat
  • 483
  • 3
  • 12
1

try

newtest = [x[0] for x in df]

you need to access the first element of the list and use that instead of the whole list

AntiMatterDynamite
  • 1,495
  • 7
  • 17
0

You have lists of one element. x[:-1] returns the list without the last element, so just an empty list. Instead, do [x[0] for x in df] or [x for x, in df]

blue_note
  • 27,712
  • 9
  • 72
  • 90
0

You could use list comprehension to remove the square brackets:

df = pd.read_excel("filename.xlsx", sheetname="Sheet1")
df = df.values.tolist()
df = [x[0] for x in df]
print(df)

This works because every element in df is a list containing one item.

Joel
  • 1,564
  • 7
  • 12
  • 20