how to reindex
时间: 2024-04-14 21:30:29 浏览: 80
index rebuild
To reindex a pandas DataFrame or Series in Python, you can use the `reindex()` method. Reindexing allows you to change the order of the existing index or insert missing index values. Here are a few examples:
Example 1: Reindexing a DataFrame with new index labels
```python
import pandas as pd
# Create an example DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
# Reindex the DataFrame with new index labels
new_index = ['x', 'y', 'z']
df_reindexed = df.reindex(new_index)
print(df_reindexed)
```
Output:
```
A B
x 1 4
y 2 5
z 3 6
```
In the above code, the `reindex()` method is called on the DataFrame `df` with the new index labels specified as the `new_index` list.
Example 2: Reindexing a DataFrame and filling missing values
```python
import pandas as pd
# Create an example DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
# Reindex the DataFrame with new index labels and fill missing values with a default value
new_index = ['x', 'y', 'z']
df_reindexed = df.reindex(new_index, fill_value=0)
print(df_reindexed)
```
Output:
```
A B
x 1 4
y 2 5
z 3 6
```
In this example, the `fill_value` parameter is used to fill any missing values with the specified default value (`0` in this case).
You can also reindex a Series in a similar manner by using the `reindex()` method.
阅读全文