Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas replace column values with a list

I have a dataframe df where some of the columns are strings and some are numeric. I am trying to convert all of them to numeric. So what I would like to do is something like this:

col = df.ix[:,i]
le = preprocessing.LabelEncoder()
le.fit(col)
newCol = le.transform(col)
df.ix[:,i] = newCol

but this does not work. Basically my question is how do I delete a column from a data frame then create a new column with the same name as the column I deleted when I do not know the column name, only the column index?

like image 403
user3494047 Avatar asked Jun 17 '17 19:06

user3494047


People also ask

How do I change a column to a list in Pandas?

values. tolist() you can convert pandas DataFrame Column to List. df['Courses'] returns the DataFrame column as a Series and then use values. tolist() to convert the column values to list.

How do I replace a value in a column with another value in Pandas?

DataFrame. replace() function is used to replace values in column (one value with another value on all columns). This method takes to_replace, value, inplace, limit, regex and method as parameters and returns a new DataFrame. When inplace=True is used, it replaces on existing DataFrame object and returns None value.


2 Answers

This should do it for you:

# Find the name of the column by index
n = df.columns[1]

# Drop that column
df.drop(n, axis = 1, inplace = True)

# Put whatever series you want in its place
df[n] = newCol

...where [1] can be whatever the index is, axis = 1 should not change.

This answers your question very literally where you asked to drop a column and then add one back in. But the reality is that there is no need to drop the column if you just replace it with newCol.

like image 84
elPastor Avatar answered Sep 18 '22 06:09

elPastor


newcol = [..,..,.....]

df['colname'] = newcol

This will keep the colname intact while replacing its contents with newcol.

like image 39
Sree Charan Avatar answered Sep 21 '22 06:09

Sree Charan