学习pandas-索引操作

瘦欲@ 提交于 2019-12-03 08:39:59
import pandas as pd
df1 = pd.DataFrame(
        {'var1':1.0,
         'var2':[1,2,3,4],
         'var3':['test','tran','test','tran'],
         'var4':'cons'},
         index = ['a','b','c','d']        
        )


df2 = pd.read_csv('123.csv',encoding='utf-8',index_col='店家')

设置索引

‘’’
df.set_index(
keys:colums be assigned as index, composite index need list type
drop = True:if or not delet the columns after creat index
append = False:if or not add index on the base of original index,replace is default
inplace = False:if or not directly modify original df
)
‘’’

df2_new = df2.set_index('地址')
df2_new1 = df2.set_index('地址',append = True,drop = False)
print(df2_new1)

restore index to columns

‘’’
df.reset_index(
drop = False:if or not delet index directly,do not restore to columns
inplace = False:if or not directly modify original df
level = None:specify restore which level to columns,for composite index
)
‘’’

df2_copy = df2.copy()
df2_copy.set_index('电话',inplace = True,append=True)
'''print(df2_copy)'''

#df2_copy.reset_index(inplace = True)

'''print(df2_copy.reset_index(level = ['电话']))'''
print(df2_copy.index)

modify index names

‘’‘df2_copy.index.names = []’’’

modify index values (replace all in essense)

df1.index = [‘a’,‘b’,‘c’,‘new’]
print(df1.index)

forced index change

‘’’
df.reindex(
labels:Like array structure,to rebuild index
axis: for which axis to rebuild
(‘index’,‘columns’) or number (0,1)
copy=True:create nem object,do not change original df
level:levels to be rebuild
#missing value
method:
pad/ffill(use the foregoing data );backfill/bfill(use back data);nearest(use nearist data)
fill_value = np.NaN:(value to fill in )
limit = None:max_step size to find value to fill in

)
‘’’

print(df1.reindex())

print(df1.reindex([‘a’,‘b’,‘c’,‘u’],fill_value=‘jon_skeet’))


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!