Python Pandas: convert list of objects to a list of integer

pandas to list
python convert list to list of strings
convert string list to int list python
python convert list index to integer
pandas convert array to list
python convert list of chars to list of ints
converting a string list to integer list in python
pandas convert list to string

Hi I have a prboblem to convert list of objects to a list of integers. The objects are within the "stopsequence" column of the Pandas data frame "Kanten". All of this I receive after so CSV importing and data cleaning in the column. I am using Python 3.X

I am a Python newbie, maybe that's part of the problem here.

import pandas as pd
import numpy as np
import os
import re
import ast
orgn_csv = pd.read_csv(r"Placeholder path for csv file")
df = orgn_csv.dropna()
Kanten = pd.DataFrame({"stopsequence" : df.stopsequence})

# In between is a block in which I use regular expressions for data cleaning purposes.
# I left the data cleaning block out to make the post shorter


Kanten.stopsequence = Kanten.stopsequence.str.split (',')
print (Kanten.head())
print (Kanten.stopsequence.dtype)                      

This gives the following output:

                                        stopsequence
2  [67, 945, 123, 122, 996, 995, 80, 81, 184, 990...
3  [67, 945, 123, 122, 996, 995, 80, 81, 184, 990...
4  [67, 945, 123, 122, 996, 995, 80, 81, 184, 990...
5  [67, 945, 123, 122, 996, 995, 80, 81, 184, 990...
6  [67, 945, 123, 122, 996, 995, 80, 81, 184, 990...
object

I am looking for a way to transform the list which contains objects. I searched through the StackOverflow Forum intensively and tried a bunch of different approaches. With none of them I was succesfull. I tryed to use:

astype(str).astype(int)

Kanten.stopsequence = Kanten.stopsequence.astype(str).astype(int)
This Returns:
ValueError: invalid literal for int() with base 10:

adapted the following post with the use of atoi instead of atof

Kanten.stopsequence.applymap(atoi)
This Returns:
AttributeError: 'Series' object has no attribute 'applymap'

list(map())

Kanten.stopsequence = list(map(int, Kanten.stopsequence))
This returns:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

apply(ast.literal_eval)

Kanten.stopsequence = Kanten.stopsequence.apply(ast.literal_eval)
This returns:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

Does anybody see a solution for that? I am uncertain if it's a complicated case or I just lacke some further programming experience. If possible a short explanation would be helpful. That I can find a solution myself againg. Thank you in advance.

A pandas Series can be trivially converted to a list, and a list of lists can be given as input to create a DataFrame.

I think this could help:

splitted = pd.DataFrame(Kanten.stopsequence.str.split (','), index=Kanten.index).astype(int)

This gives you a new dataframe with same index as the original one but where each element is in its own column.

If relevant, you could then concat that new columns

pd.concat([Kanten, splitted], axis=1)

Convert pandas.DataFrame, Series and list to each other, pandas.DataFrame,pandas.Series and Python's built-in type list can be a list type object to the first argument of each constructor pandas. Interconversion between data types is facilitated by python libraries quite easily. But the problem of converting the entire list of string to integers is quite common in development domain.

So from your second attempt at manipulating the data, your error message tells you that Kanten.stopsequence is a Series, not a DataFrame. To convert, you'd need to access

list_of_lists = Kanten.stopsequence.to_numpy(dtype='int32').tolist()

Note that for your data this will create a nested 2d data array. To access the first integer from the first row, you would need to write list_of_lists[0][0].

Python, A Series is a one-dimensional labeled array capable of holding any data type ( integers, strings, floating point numbers, Python objects, etc.). It has to be remembered that unlike Python lists, a Series will always contain data of the same type. Python | Pandas Series.astype() to convert Data type of series� Let’s now review few examples with the steps to convert a string into an integer. Steps to Convert String to Integer in Pandas DataFrame Step 1: Create a DataFrame. To start, let’s say that you want to create a DataFrame for the following data:

This is how I would approach pulling the last column of a DataFrame into a list of ints.

Let's say the .csv is located in the same directory as your .py script and it's called kanten.csv. The column you're looking for is stopsequence.

import os
import pandas as pd

path=os.getcwd()
filename = 'kanten.csv'
filepath = os.path.join(path, filename)

kanten = pd.read_csv(filepath)
list = list(kanten['stopsequence'].apply(lambda x: int(x)))

In the last line, the stopsequence column is pulled from kanten, the values are casted as integers, then the column is converted to a standard python list object.

Creating a Pandas Series from Lists, At times, you may need to convert Pandas DataFrame into a list in Python. But how would you do that? To accomplish this task, you can use tolist as follows: You then decided to capture that data in Python using Pandas DataFrame. At a certain point, you realize that you’d like to convert that Pandas DataFrame into a list. To accomplish this goal, you may use the following Python code, which will allow you to convert the DataFrame into a list, where:

How to Convert Pandas DataFrame into a List, Converting a list of integers into one integer combines them. For example, converting [1, 2, 3] into one integer results in 123 . Use int() to convert� Another approach to convert a list of multiple integers into a single integer is to use map() function of Python with str function to convert the Integer list to string list. After this, join them on the empty string and then cast back to integer.

How to convert a list of integers into a single integer in Python, Lists can be converted to arrays using the built-in functions in the Python numpy library. numpy provides us with two functions to use when converting a list into an array: np.array() will make a copy of the object (by default) and convert that to an array, while np.asarray() will not. Data Analysis & Processing with Pandas. pandas.DataFrame,pandas.Series and Python's built-in type list can be converted to each other.Here, the following contents will be described.Convert list to pandas.DataFrame, pandas.SeriesFor data-only listFor list containing data and labels (row / column names) For data-only list For list containin

How to convert a list to an array in Python, In this post, we will see how to convert a list of string into a list of integers in Python. For example, ['1', '2', '3', '4', '5'] should be converted into [1, 2, 3, 4, 5]. Python’s pandas library provide a constructor of DataFrame to create a Dataframe by passing objects i.e. pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False) Here data parameter can be a numpy ndarray , dict, or an other DataFrame.

Comments
  • A sample of stopsequence?
  • You say you import this data from a CSV file. Why are you not creating the DataFrame directly from the CSV?
  • @DirtyBit Do you mean a sample of the original values which I loaded in from the CSV file?
  • @emporerblk I added the read_csv as well to make it more clear what I am doing. I am kind of learning while I am doing it. So it is definitely possible that I am doing things which are not 'ideal'.