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

Time:02-19

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:

     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

CodePudding user response:

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
  • Related