Home > Enterprise >  Getting error: Length of values (1) does not match length of index (9)
Getting error: Length of values (1) does not match length of index (9)

Time:09-23

Write a Pandas program to find the positions of numbers that are multiples of 5 of a given series.

I am getting this error "ValueError: Length of values (1) does not match length of index (9)", how can I fix it below are the code :

import pandas as pd
import numpy as np
num_series = pd.Series(np.random.randint(1, 10, 9))
print("Original Series:")
print(num_series)
result = np.argwhere(num_series % 5==0)
print("Positions of numbers that are multiples of 5:")
print(result)

CodePudding user response:

A pd.Series cannot be passed directly to np.argwhere, convert Series.to_numpy first:

result = np.argwhere(num_series.to_numpy() % 5 == 0)

Alternatively we can simply mask the index of the Series and convert the filtered pd.Index to_numpy if needed:

result = num_series.index[num_series % 5 == 0].to_numpy()

Sample output:

import numpy as np
import pandas as pd

num_series = pd.Series(np.random.randint(1, 10, 9))
print("Original Series:")
print(num_series)
result = np.argwhere(num_series.to_numpy() % 5 == 0)
print("Positions of numbers that are multiples of 5:")
print(result)
Original Series:
0    7
1    8
2    5
3    7
4    8
5    6
6    8
7    6
8    8
dtype: int32
Positions of numbers that are multiples of 5:
[[2]]

import numpy as np
import pandas as pd

num_series = pd.Series(np.random.randint(1, 10, 9))
print("Original Series:")
print(num_series)
result = num_series.index[num_series % 5 == 0]
print("Positions of numbers that are multiples of 5:")
print("pd.Index:", result)
print("to_numpy:", result.to_numpy())
Original Series:
0    6
1    8
2    4
3    3
4    9
5    5
6    2
7    8
8    8
dtype: int32
Positions of numbers that are multiples of 5:
pd.Index: Int64Index([5], dtype='int64')
to_numpy: [5]

CodePudding user response:

Try using:

# Solution 1:
res = np.argwhere(num_series.to_numpy() % 5 == 0)

# Solution 2:
res = num_series[num_series % 5 == 0]

Apparently when you are using np.argwhere, you pass a pd.Series into the np.nonzero function which will try to reconstruct the series, but will fail. Previously there existed a nonzero method for pd.Series but it has been deprecated (https://pandas.pydata.org/pandas-docs/version/0.25.3/reference/api/pandas.Series.nonzero.html#pandas-series-nonzero).

  • Related