2016-11-16 60 views
1

我有一个有120列的熊猫数据框。列看起来是这样的:如何用玩具名称重新命名长熊猫数据框?

0_x  1_x  2_x  3_x  4_x  5_x  6_x  7_x  8_x  0_y  ...  65 ... 120 

我怎样才能在一次运动中重命名它们?我阅读文档,发现大熊猫重命名列的方法是:

df.columns = ['col1', 'col2', 'col3'] 

的问题是,我写120个多列的列表可能是非常奇怪的。这个问题有哪些替代方案?假设我想列出所有列,如:col1colN

回答

5

很容易的用一个列表理解和枚举或范围:

df.columns = ['col%s' % i for i in range(len(df.columns))] 
df.columns = ['col%s' % i for i, c in enumerate(df.columns)] 

我喜欢列举,即使你是刚刚扔掉的列名。没有确定的理由,我只是不喜欢func(func(something))的外观,当我可以的时候避免它。

+1

您不必在枚举中指定'c',而是可以使用'df.columns = ['cols%s'%i for i,__ in enumerate(df.columns)''向读者发信号你扔掉变量。尽管个人喜好:http://stackoverflow.com/questions/5893163/what-is-the-purpose-of-the-single-underscore-variable-in-python – TheF1rstPancake