How to set the indices of data frames in Python?

In Python, you can use the Pandas library to manipulate data frames. The index of a data frame can be set using the following methods:

  1. Using the default index: When creating a data frame, if an index is not specified, the default integer index will be used.
import pandas as pd

# 创建数据帧
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
print(df)

Output:

   A  B
0  1  4
1  2  5
2  3  6
  1. indicator
import pandas as pd

# 创建数据帧并指定索引
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}, index=['a', 'b', 'c'])
print(df)

Result:

   A  B
a  1  4
b  2  5
c  3  6
  1. Assign an index to the data frame
import pandas as pd

# 创建数据帧
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

# 重新设置索引
df = df.set_index('A')
print(df)

Output:

   B
A   
1  4
2  5
3  6
  1. Reset the index
import pandas as pd

# 创建数据帧并指定索引
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}, index=['a', 'b', 'c'])

# 重置索引
df = df.reset_index()
print(df)

Output:

  index  A  B
0     a  1  4
1     b  2  5
2     c  3  6
Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds