0

Example:

Column 1

[1, 3, " "]

[2, " ", 3]

etc.

Is there a quick list compehension where I can keep just the integers?

Prince Vegeta
  • 719
  • 6
  • 21
vstone
  • 11
  • Just to clarify, do you want to remove the space chars or keep only ints? What do you want to happen when you have an int in a string (e.g "3") ? – ds4940 Nov 20 '19 at 15:12
  • `df['Column 1] = [[x for x in i if isinstance(x, int)] for i in df['Column 1']]` ..? – Chris Adams Nov 20 '19 at 15:14
  • @ds4940 just keep the ints – vstone Nov 20 '19 at 16:30
  • @ChrisA that wouldn't work since it doesn't look within each array in each row. That solution returned a column with an empty array in each row – vstone Nov 20 '19 at 16:36

1 Answers1

0

You are probably looking for something like so:

a = [1, 3, " "]
b = [i for i in a if i != " "]

print(b) #> [1, 3]

If you want to include other spaces to remove:

a = [1, 3, " ", ""]
b = [i for i in a if i not in (" ", "")]

If you want to only add int (if there are str, float, etc. this method will not generalize):

a = [1, 3, " ", ""]
b = [i for i in a if isinstance(i, int)]
felipe
  • 7,324
  • 2
  • 28
  • 37
  • As my structure is a Dataframe series, this approach doesn't work. In theory your solution makes sense, but how would you change it for a Dataframe series? i.e. the series is a column where each row is an array – vstone Nov 20 '19 at 16:33
  • Does your dataframe just have a single column? You will need to use a method similar to he answer in this question https://stackoverflow.com/questions/16476924/how-to-iterate-over-rows-in-a-dataframe-in-pandas to iterate (loop) over each of the elements (which themselves are a list) and modify them. – ds4940 Nov 21 '19 at 10:19
  • @vstone If you edit your answer with the code you used to initialize the `DataFrame` (reply here if you did), I could come back and edit these answers to help you out further -- otherwise, I'm honestly unsure how you have your `df` setup. – felipe Nov 21 '19 at 13:40