---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-13-a1c35869ebbd> in <module>
----> 1 df.index[1] = "20211001"
~/miniconda3/lib/python3.7/site-packages/pandas/core/indexes/base.py in __setitem__(self, key, value)
3907
3908 def __setitem__(self, key, value):
-> 3909 raise TypeError("Index does not support mutable operations")
3910
3911 def __getitem__(self, key):
TypeError: Index does not support mutable operations
df.columns[1]
'B'
df.columns[1]="F"
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-15-e4a0ff29c1bd> in <module>
----> 1 df.columns[1] = "F"
~/miniconda3/lib/python3.7/site-packages/pandas/core/indexes/base.py in __setitem__(self, key, value)
3907
3908 def __setitem__(self, key, value):
-> 3909 raise TypeError("Index does not support mutable operations")
3910
3911 def __getitem__(self, key):
TypeError: Index does not support mutable operations
#我想改动index name,发现上述操作行不通,然后pandas提供了reindex接口#To reindex means to conform the data to match a given set of labels along a particular axis.#也就是说reindex相当于在指定轴上select,当没有的index出现则填充Nan#我们再试一下会不会改动原来的dataframe
df.reindex(["C","A","E"],axis="columns")
C
A
E
2021-08-21
-0.828510
0.291046
NaN
2021-08-22
-0.009343
0.169817
NaN
2021-08-23
-0.564575
0.539149
NaN
2021-08-24
0.387748
-0.696348
NaN
2021-08-25
0.673211
-0.756739
NaN
2021-08-26
0.659946
1.342560
NaN
df
#此时可以看到原来的dataframe并没有改变
A
B
C
D
2021-08-21
0.291046
-1.182064
-0.828510
-0.050328
2021-08-22
0.169817
0.372991
-0.009343
0.667243
2021-08-23
0.539149
-1.772332
-0.564575
-0.136001
2021-08-24
-0.696348
1.387040
0.387748
0.159869
2021-08-25
-0.756739
0.313842
0.673211
0.799936
2021-08-26
1.342560
0.528175
0.659946
1.509831
df.reindex([0,5],axis="index")#此时使用数字索引好像失效了
A
B
C
D
0
NaN
NaN
NaN
NaN
5
NaN
NaN
NaN
NaN
df.reindex(index=["2021.08.21","2021.08.26"],columns=["A","D"])#index name 我打不出正确的格式,哈哈哈
A
D
2021.08.21
NaN
NaN
2021.08.26
NaN
NaN
#骚操作1#Note that the Index objects containing the actual axis labels can be shared between objects. So if we have a Series and a DataFrame#rs = s.reindex(df.index)#This means that the reindexed Series’s index is the same Python object as the DataFrame’s index.
A B C
a -0.556821 1.481807 0.175237
b -0.440093 1.309766 0.265040
c -0.298950 0.565390 1.164518
d -0.287415 -0.226004 0.875915
A C E F
a -1.220393 -0.770392 -0.160964 0.344573
c 0.232881 -0.972749 1.882510 0.115421
e 0.265853 -1.628597 -1.128498 -0.073716
f -0.189951 -0.496491 -0.109640 -1.529581