我正在制定固定转售价格dataset https://data.gov.sg/dataset/resale-flat-prices(如果您有兴趣,我使用的是 2015 年 1 月以后的数据)。
First, I group the data by using
data.groupby('flat_type').sum()
, Then the data becomes:
我尝试交换行
现在,我尝试使用以下答案交换最后两行这个帖子 https://stackoverflow.com/questions/46890972/swapping-rows-within-the-same-pandas-dataframe:
b,c = data_by_type.iloc[-2], data_by_type.iloc[-1]
temp = data_by_type.iloc[-2].copy()
data_by_type.iloc[-2] = c
data_by_type.iloc[-1] = b
最后两行的内容发生了更改,但最后两行的索引保持不变。
所以我的问题是:如何交换整行,包括索引?
Use np.r_ https://docs.scipy.org/doc/numpy/reference/generated/numpy.r_.html:
df = df.iloc[np.r_[0:len(df) - 2, -1, -2]]
选择:
df = df.loc[df.index[:-2].tolist() + df.index[-1:].tolist() + df.index[-2:-1].tolist()]
print (df)
floor_area_sqm lease_commence_date remaining_lease \
flat_type
1 ROOM 1085.0 69125 1977
2 ROOM 40898.0 1788955 62356
3 ROOM 1430010.1 41448329 1344374
4 ROOM 3226160.4 67177320 2604002
5 ROOM 2349460.0 39663269 1555300
MULTI-GENERATION 4105.0 49677 1708
EXECUTIVE 943961.0 13059434 495628
resale_price
flat_type
1 ROOM 6.938000e+06
2 ROOM 2.168112e+08
3 ROOM 6.628663e+09
4 ROOM 1.460442e+10
5 ROOM 1.043298e+10
MULTI-GENERATION 1.969189e+07
EXECUTIVE 4.101716e+09
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)