Home > OS >  i try to set multiply values using DataFrame.loc in pandas but "Must have equal len keys and va
i try to set multiply values using DataFrame.loc in pandas but "Must have equal len keys and va

Time:08-25

When i do the following code:

df = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'],
 'a': [18, 22, 19, 14, 14, 11, 20, 28, 22],
 'b': [5, 7, 7, 9, 12, 9, 9, 4, 8],
 'c': [11, 8, 10, 6, 6, 5, 9, 12, 9]})

df.loc[(df.b>8), ["one", "two"]] = df.c, df.a
df.loc[(df.b<=8), ["one", "two"]] = df.b*5, df.c*10
print(df)

I got ValueError: Must have equal len keys and value when setting with an ndarray

What is wrong?

If i do:

df.loc[(df.b>8), ["one", "two"]] = df.c
df.loc[(df.b<=8), ["one", "two"]] = df.b

it works

CodePudding user response:

You can't due to index alignment.

You would need to use:

df.loc[(df.b>8), ["one", "two"]] = df[['c', 'a']].set_axis(['one', 'two'], axis=1)
df.loc[(df.b<=8), ["one", "two"]] = df[['b', 'c']].mul([5,10]).set_axis(['one', 'two'], axis=1)

Alternative with numpy.where:

df[['one', 'two']] = np.where(np.tile(df['b'].gt(8), (2, 1)).T,
                              df[['c', 'a']], df[['b', 'c']].mul([5,10]))

output:

  team   a   b   c  one  two
0    A  18   5  11   25  110
1    B  22   7   8   35   80
2    C  19   7  10   35  100
3    D  14   9   6    6   14
4    E  14  12   6    6   14
5    F  11   9   5    5   11
6    G  20   9   9    9   20
7    H  28   4  12   20  120
8    I  22   8   9   40   90
  • Related