pandas的Series的reset_index和reindex
一、修改series的index的函数reset_index的用法。import pandas as pd
idx ="hello the cruel world".split()
val =
t = pd.Series(val, index = idx)
print (t, "<- t")
print (t.reset_index(), "<- reset_index")
print (t.reset_index(drop = True), "<- reset_index")
print (t, "<- t")
这里启用reset_index函数的drop形参去掉之前的index,还可以启用inplace直接影响原series对象。
二、reindex函数可以将series的index换成其他的index。新的series保留原series存在的index的values值,
如果新的index没在原series的index里填充NaN值,或者使用fill_value参数指定填充值。
import pandas as pd
idx ="hello the cruel world".split()
val =
t = pd.Series(val, index = idx)
idn = "hello python nice world".split()
print (t, "<- t")
print (t.reindex(idn), "<- reindex")
print (t.reindex(idn, fill_value = -1), "<- reindex")
print (t, "<- t")
输出结果:
hello 1000
the 201
cruel NaN
world 104
dtype: float64 <- t
hello 1000
python NaN
nice NaN
world 104
dtype: float64 <- reindex
hello 1000
python -1
nice -1
world 104
dtype: float64 <- reindex
hello 1000
the 201
cruel NaN
world 104
dtype: float64 <- t
页:
[1]