Home > Back-end >  how to replace values of an individual row and specific columns in pandas data frame
how to replace values of an individual row and specific columns in pandas data frame

Time:05-23

I have a data frame with 902 columns. I want to replace all the values of row 0 from columns 214 to 902 by the values stored in a list. For instance:

I have a list like this:

list_a=['item0','item1','item2', 'item3'....'item 688']

I have a data frame like this:

 item0 item1 item2 item3 ...item688
0  x.    y.    z.    w.       i
1  x.    y.    z.    w.       i
2  x.    y.    z.    w.       i
3  x.    y.    z.    w.       i
4  x.    y.    z.    w.       i

my desired output is:

  item0 item1 item2 item3 ...item688
0 item0 item1 item2 item3 ...item688
1  x.     y.    z.    w.       i
2  x.     y.    z.    w.       i
3  x.     y.    z.    w.       i
4  x.     y.    z.    w.       i

Note: The items stored in the list are also the names of the data frame columns from 214 to 902

I tried, but that does not work:

df.iloc[0,214:902] = list_a

How can I achieve this goal? Any help I appreciate!!

CodePudding user response:

ok that is very strange than your solution works with this simple test:

import pandas as pd

df = pd.DataFrame({
    'colA':[True, False, False], 
    'colB': [1, 2, 3],
    'colc':[True, False, False], 
    'colD': [1, 2, 3]
})

df.iloc[0, 1:3] = ['test 1', 'test 2']

The resulting data frame changed from:

    colA    colB    colc    colD
0   True    1   True    1
1   False   2   False   2
2   False   3   False   3

to:

    colA    colB    colc    colD
0   True    test 1  test 2  1
1   False   2   False   2
2   False   3   False   3

That would solve your problem if i am not mistaken right? Can you check or verify your results some how again?

A possible problem might arise with your iloc command because if you want to change column 902 as well, you would have to say df.iloc[0, 212:903]. You could check this with len(df.iloc[0, 1:3]) and len(list_a) to verify that they have the same length.

CodePudding user response:

My solution works:

df.iloc[0,214:902]= list_a
  • Related