pandas 中 df.reindex() 和 df.set_index() 方法的区别

Difference between df.reindex() and df.set_index() methods in pandas

我被这个弄糊涂了,这很简单,但我没有立即在 Whosebug 上找到答案:

但是,df.reindex(myList) 也会将值更改为 NA。一个简单的替代方法是:df.index = myList

我希望这个 post 能说明问题!也欢迎对此 post 进行补充!

你可以在一个简单的例子中看出区别。让我们考虑这个数据框:

df = pd.DataFrame({'a': [1, 2],'b': [3, 4]})
print (df)
   a  b
0  1  3
1  2  4

然后索引为 0 和 1

如果您对 'a' 列使用 set_index,则索引为 1 和 2。如果您使用 df.set_index('a').loc[1,'b'],您将得到 3。

现在如果你想使用具有相同索引 1 和 2 的 reindex,例如 df.reindex([1,2]),当你执行 df.reindex([1,2]).loc[1,'b']

时,你将得到 4.0

发生的事情是 set_index 已将之前的索引 (0,1) 替换为 (1,2)(来自 'a' 列的值),但未触及 'a' 列中值的顺序=38=]

df.set_index('a')
   b
a   
1  3
2  4

虽然 reindex 更改了索引,但保留列 'b' 中的值与原始 df

中的索引相关联
df.reindex(df.a.values).drop('a',1) # equivalent to df.reindex(df.a.values).drop('a',1)
     b
1  4.0
2  NaN
# drop('a',1) is just to not care about column a in my example

最后,reindex 更改索引的顺序而不更改与每个索引相关联的行的值,而 set_index 将使用列的值更改索引,而不改变顺序数据框中的其他值

只是添加,撤消到 set_index would be reset_index 方法(或多或少):

df = pd.DataFrame({'a': [1, 2],'b': [3, 4]})
print (df)

df.set_index('a', inplace=True)
print(df)

df.reset_index(inplace=True, drop=False)
print(df)

   a  b
0  1  3
1  2  4
   b
a   
1  3
2  4
   a  b
0  1  3
1  2  4

除了 Ben 的精彩回答。 T,我想再举一个例子,说明当你对索引列

使用reindexset_index时它们有何不同
import pandas as pd
import numpy as np
testdf = pd.DataFrame({'a': [1, 3, 2],'b': [3, 5, 4],'c': [5, 7, 6]})

print(testdf)
print(testdf.set_index(np.random.permutation(testdf.index)))
print(testdf.reindex(np.random.permutation(testdf.index)))

输出:

  • 使用set_index,当index列(第一列)打乱后,其他列的顺序保持不变
  • 使用 reindex,行的顺序会根据 index 列的随机顺序进行相应更改。
   a  b  c
0  1  3  5
1  3  5  7
2  2  4  6
   a  b  c
1  1  3  5
2  3  5  7
0  2  4  6
   a  b  c
2  2  4  6
1  3  5  7
0  1  3  5