0

I have a dataframe df1 like

  A B
1 2 3
2 9 8

and an object ob (dtype: object)

1 5
2 4

replacing column B in the dataframe with df1['B'] = ob doesn't work despite all columns of the dataframe are also objects as df1.dtypes tells me and they have the same length. What am I doing wrong?

Fred
  • 417
  • 5
  • 16

2 Answers2

1

It will be difficult to tell you what is going wrong without knowing how the ob object is made, the object dtype has a very broad definition. Replacing a column is easy if you can convert the ob object to a pandas dataframe:

t = pd.DataFrame([[2,3],[9,8]],columns = ['A','B'])    
o = pd.DataFrame([[5],[4]])
t['B'] = o
print(t)

Yields

   A  B
0  2  5
1  9  4
JaHoff
  • 196
  • 5
  • thanks, this worked. Though I had to turn off this message: _A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead_ with `pd.options.mode.chained_assignment = None # default='warn'` [see here]( https://stackoverflow.com/questions/20625582/how-to-deal-with-settingwithcopywarning-in-pandas) – Fred Jan 05 '21 at 13:19
0

I don't know if you can replace a column with another but here's a method to replace values.

df['column name'] = df['column name'].replace(['1st old value','2nd old value',...],['1st new value','2nd new value',...])
omar-h-omar
  • 84
  • 1
  • 2
  • 11