Length of values does not match length of index
时间: 2023-12-15 22:06:35 浏览: 125
This error message occurs when the number of elements in a list or array provided as values does not match the number of elements in the index.
For example, if we have a pandas DataFrame with an index of length 5 and we try to assign a list of length 4 as a new column, we will get this error:
```
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': [6, 7, 8, 9, 10]})
df['C'] = [11, 12, 13, 14] # Error: Length of values does not match length of index
```
To fix this error, we need to make sure that the length of the values matches the length of the index:
```
df['C'] = [11, 12, 13, 14, 15] # No error
```
Alternatively, we can provide a Series as the new column, which will automatically align with the existing index:
```
df['C'] = pd.Series([11, 12, 13, 14], index=df.index) # No error
```
阅读全文