Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fill the rightmost column with values in pandas

There is an unknown number of columns, and each row has exactly one value.

However, I cannot tell which column the number is in.

I would like to know how to fill one value from each row into the rightmost column.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The example below consists of three columns, but I don’t know how many there actually are.

import pandas as pd
import io

temp = u"""
col1,col2,col3
nan,nan,3
nan,4,nan
1,nan,nan
"""

data = pd.read_csv(io.StringIO(temp), sep=",")

# data
# Out[31]: 
#    col1  col2  col3
# 0   NaN   NaN   3.0
# 1   NaN   4.0   NaN
# 2   1.0   NaN   NaN


What I want:

# data2
#     col3
# 0    3.0
# 1    4.0
# 2    1.0

>Solution :

Since you know you have exactly one value in each row, you can add all the rows.

import pandas as pd
import io

temp = u"""
col1,col2,col3
nan,nan,3
nan,4,nan
1,nan,nan
"""

data = pd.read_csv(io.StringIO(temp), sep=",")

data['col4'] = data.sum(axis=1, numeric_only=True)

One more way is to :

data['col4'] = data.loc[:,[*data.columns.values]].sum(axis=1)

Output

enter image description here

pandas.DataFrame.sum

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading