繁体   English   中英

使用Pandas Dataframe列创建新的复杂索引

[英]Creating new complex index with pandas Dataframe columns

我正在尝试将数据框中的列“ 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  |  ...

期望的结果将是一个类似于以下结果的数据框:

         A  |  B  |  C  |  ...
-------------------------------
 05000   5  | djn |  0  |  ...
 05001   5  | vlv |  1  |  ...
 05002   5  | bla |  2  |  ...
 05003   5  | ses |  3  |  ...
 05004   5  | dug |  4  |  ...

我已经睁开眼睛,有人知道如何操纵数据框来获得这样的结果吗?

#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 ....,或者对多列进行排序或分组会更安全)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM