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

Keep getting Wrong number of items passed 2, placement implies 1 when adding new column

I have the following dataframe where I’m converting positive values to negative and negative values to positive.

d = {'epi':[-1.343, -7.334, -1.2, 4.5, -1.1]}
x = pd.DataFrame(d)

When I insert the first column its fine:

x.epi = x.epi.astype(str)
x['negs_to_pos'] = x.loc[x.epi.str.contains('-')].astype(float).abs()

resulting in:

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

     epi      negs_to_pos
0   -1.343    1.343
1   -7.334    7.334
2   -1.2      1.200
3    4.5      NaN
4   -1.1      1.100

However, when I go to add in another column I get an error:

x['pos_to_neg'] = x.loc[~x.epi.str.contains('-')]
x['pos_to_neg'] = '-' + x['pos_to_neg']

ValueError: Wrong number of items passed 2, placement implies 1

I can’t seem to figure this out…

Desired output:

     epi      negs_to_pos    pos_to_negs
0   -1.343    1.343          NaN  
1   -7.334    7.334          NaN
2   -1.2      1.200          NaN
3    4.5      NaN            -4.5
4   -1.1      1.100          NaN

>Solution :

You can try return Series instead one column DataFrame if add epi to loc:

x['pos_to_neg'] = x.loc[~x.epi.str.contains('-'), 'epi']

Simplier solution:

m = x.epi < 0
x['negs_to_pos'] = -x.loc[m, 'epi']
x['pos_to_neg'] =  -x.loc[~m, 'epi']
print (x)
     epi  negs_to_pos  pos_to_neg
0 -1.343        1.343         NaN
1 -7.334        7.334         NaN
2 -1.200        1.200         NaN
3  4.500          NaN        -4.5
4 -1.100        1.100         NaN
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