我正在尝试连接数据框中的列'A'和'C',如下所示,将其用作新索引:
A | B | C | ...
---------------------------
0 5 | djn | 0 | ...
1 5 | vlv | 1 | ...
2 5 | bla | 2 | ...
3 5 | ses | 3 | ...
4 5 | dug | 4 | ...
所需的结果将是一个类似于以下结果的Dataframe:
A | B | C | ...
-------------------------------
05000 5 | djn | 0 | ...
05001 5 | vlv | 1 | ...
05002 5 | bla | 2 | ...
05003 5 | ses | 3 | ...
05004 5 | dug | 4 | ...
我已经搜索过我的眼睛,有人知道如何操纵数据帧来获得这样的结果吗?
答案 0 :(得分:2)
#dummying up a dataframe
cf['A'] = 5*[5]
cf['C'] = range(5)
cf['B'] = list('qwert')
#putting together two columns into a new one -- EDITED so string formatting is OK
cf['D'] = map(lambda x: str(x).zfill(5), 1000*cf.A + cf.C)
# use it as the index
cf.index = cf.D
# we don't need it as a column
cf.drop('D', axis=1, inplace=True)
print(cf.to_csv())
D,A,C,B 05000,5,0,q 05001,5,1,w 05002,5,2,e 05003,5,3,r 05004,5,4,t
那就是说,我怀疑你使用多索引更安全(如果B中的值超过999 ......),或者对多列进行排序或分组。