本來是一項很簡單的任務。。。但很容易忘記搞混。。所以還是記錄一下
方法一:
df['col'].value_counts()
方法二:
groups = df.groupby('col') groups.size() # 這里很容易就用上counts所以錯誤...
對index進行更改:
df2.index = df2.index.map(f) # f為函數
按值排序
基本語法:by='name' 指定按該行/列來排序; 默認ascending=True,升序排序;
>>> df3 = pd.DataFrame(np.random.randint(0,10,(4, 3)), columns=list('bde'), index=range(4)) >>> df3 b d e 0 3 6 7 1 7 7 2 2 4 5 4 3 1 0 3
# 默認axis=0,對col_name列進行排序,該列中每個值對應的行也跟着變動;
df.sort_index(by='col_name')
>>> df3.sort_values(by='b') b d e 3 1 0 3 0 3 6 7 2 4 5 4 1 7 7 2
# 對第row_name行進行排序,該行中每個值相應的列也跟着變動,ascending=False 降序
df.sort_index(by='row_name', axis=1, ascending=False)
>>> df3.sort_values(by=3, ascending=False, axis=1) e b d 0 7 3 6 1 2 7 7 2 4 4 5 3 3 1 0