Iloc index in pandas and modified index

iloc index

First establish the following data:

import pandas as pd

df = pd.DataFrame([['乔峰', '男', 95, '降龙十八掌', '主角'],
          ['虚竹', '男', 93, '天上六阳掌', '主角'],
          ['段誉', '男', 92, '六脉神剑', '主角'],
          ['王语嫣', '女', 95,'熟知武诀', '主角'],
          ['包不同', '男', 65, '胡搅蛮缠', '配角'],
          ['康敏', '女', 40, '惑夫妒人', '配角']],
          index=list('abcdef'.upper()),
          columns=['name', 'gender', 'score', 'skill', 'class'])
df

The results are as follows:
Insert picture description here

We are now going to index "Wang Yuyan", ilochow should it be used ?
Count it and find that its coordinates are (3,0).

df.iloc[3,0]

The result is as follows:
Insert picture description here
So serieshow does the data structure use the ilocindex?

#列索引直接得到series
dfn=df["name"]
print(type(dfn))
dfn

Insert picture description here

seriesIt ilocshould be noted that since there is only one column, the row label of iloc is written as usual. The column label must be 0, so there is no need to write it. If it is written, an error will be reported!

dfn.iloc[3]

Insert picture description here
Finally, let me remind you that ilocthe row and column labels are counted in strict order, and have .indexnothing to do with yours , even if the above data is changed .indexfrom the original [A,B,C,D,E,F] to [5,4, 3,2,1,0],dfn.iloc[0] is to output "Qiao Feng" instead of "Kang Min".

Modify index

1. Dataframe .indexassignment for overall modification.

index=[i for i in range(df.shape[0])]
df.index=index
df

Insert picture description here
Note that a single modification will report an error.

print(df.index)
df.index[3]=10

Insert picture description here
2. Use to renameachieve a single modification.

df.rename(index={
    
    3:10})

Insert picture description here
Note: There is no real modification above, the real modification can be:

df.rename(index={
    
    3:10},inplace=True)
#或者
df=df.rename(index={
    
    3:10})

Modifying the content of the columns index is similar to the index.

df.columns

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_43391414/article/details/113063543