学习pandas-索引操作

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’))


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值