0

I have a pandas Series and I would like to covert all the rows of my series into a single list. I have:

list1=Series([89.34,88.52,104.19,186.84,198.15,208.88]). Then I have a function which i call:
func(list1)
def func(list1):
   list1=list1.values.tolist()
   print(list1)

the printed result is :

[[89.34], [88.52], [104.19], [186.84], [198.15], [208.88]]

but I would like to have : [89.34,88.52,104.19,186.84,198.15,208.88]

any help. I am using python 2.7

3
  • You should not use list as a variable name because it a globally accessible data structure. Commented Aug 14, 2015 at 20:38
  • I couldn't reproduce the problem you had. Could you add python version, pandas version and what OS you use? Commented Aug 14, 2015 at 20:53
  • 1
    Yeah, I don't see how that code would give that result. If you had a DataFrame, and then called .values.tolist(), you'd get a list of lists, but if you have a Series, you should simply get a list. Commented Aug 14, 2015 at 20:55

1 Answer 1

1

Easiest way would be to access the values property of the Series object, like you have in your example.

> from pandas import Series
> a_series = Series([89.34,88.52,104.19,186.84,198.15,208.88])
> print(a_series.values.tolist())
[89.34, 88.52, 104.19, 186.84, 198.15, 208.88]

Accessing more than one elements in the list at the same time:

> counter = 0
> a_list = a_series.values.tolist()
> while(counter < len(a_list)):
..    if((counter+1) < len(a_list)):
..        print(a_list[counter] == a_list[counter+1])
..    counter+=1
False
False
False
False
False
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks Ray,the problem with this is that i would like to iterate through that list starting at the second index; that is your elem+1 and compare it with elem
Then you don't need to you a list. You can do more efficiently with pandas objects. Use b_series = a_series.shift(-1) to create series that has the same indexes, only the data is shifted. Then you can use for example a_series - b_series to get the difference
I added a way to compare elements to previous elements. If I am mistaken please let me know. Any logic requirements (like comparing elem+1 to elem) should be in your question so there is no confusion.
@Ray i have a curious question though; assuming it was a DataFrame and that i am passing just one column; how will it work?
You would have to add another loop inside the while loop since you would then be iterating over "columns" and "rows". Unless pandas has a built-in that makes this easier. I'm not that familiar with pandas to be honest. The docs have a few interesting methods mentioned (like DataFrame.applymap) that may work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.