How to transfer 1 value of a column to another column but on a specific row?

Viewed 38

I have a dataframe that consists of something like this. (an example)

    col1  col2  col3
0     1     2      1
1     2     4      2
2     3     6      3
3     4    nan    nan    <------
4     5    nan    nan
5     6    12     nan

How can I replace row index of 3 with the first column row index 3 value?

The final result that I want is:

         col1  col2  col3
    0     1     2      1
    1     2     4      2
    2     3     6      3
    3     4     4      4     <-----
    4     5    nan    nan
    5     6    12     nan
4 Answers
dataframe.iloc[3] = dataframe.iloc[3]['col1']

Yields:

   col1  col2  col3
0   1.0   2.0   1.0
1   2.0   4.0   2.0
2   3.0   6.0   3.0
3   4.0   4.0   4.0
4   5.0   NaN   NaN
5   6.0  12.0   NaN

You can do this using the below code.

import pandas as pd
df = pd.DataFrame({'col1': [1,2,3,4,5,6], 'col2':[2,4,6,0,0,12], 'col3': [1,2,3,0,0,0] })
print(df)
df.iloc[3] = df.iloc[3]['col1']
print(df)

The output will be:

   col1  col2  col3
0     1     2     1
1     2     4     2
2     3     6     3
3     4     0     0
4     5     0     0
5     6    12     0
   col1  col2  col3
0     1     2     1
1     2     4     2
2     3     6     3
3     4     4     4
4     5     0     0
5     6    12     0

you can use the iloc method to access a row with its index

    >>> df = pd.DataFrame({'Col1': [1,2,3,4,5,6], 'Col2':[0,0,0,0,0,0]})
    >>> df
       Col1  Col2
    0     1     0
    1     2     0
    2     3     0
    3     4     0
    4     5     0
    5     6     0
    >>> df.loc[0]
    Col1    1
    Col2    0
    Name: 0, dtype: int64
    >>>
    >>> df.iloc[0]
    Col1    1
    Col2    0
    Name: 0, dtype: int64
    >>>
    >>>
    >>>
    >>> df['Col2'].iloc[1] = df['Col1'].iloc[1]
    >>> df
       Col1  Col2
    0     1     0
    1     2     2
    2     3     0
    3     4     0
    4     5     0
    5     6     0
    >>>

You can also do this using numpy.where. For example the code below will replace every null value in 'col2' with the value of 'col1' at the same index:

df['col2'] = np.where(df['col2'].isnull(), df['col1'], df['col2'])

You can be more specific by with your rows by adding conditions to the first argument, so let's say you only want the 3rd index you can do something like:

df['col2'] = np.where(df['col2'].isnull() & df.index == 3, df['col1'], df['col2'])
Related