[英]When initiating a Pandas DataFrame, it automatically generates names of the columns like self.<column_name>; How?
[英]How to name Pandas Dataframe Columns automatically?
我有一个包含102列的 Pandas 数据框df
。 每列都以不同的方式命名,例如A, B, C
等,以提供以下结构的原始数据框
Column A. Column B. Column C. ....
Row 1.
Row 2.
---
Row n
我想将列名称从A, B, C
等更改为F1, F2, F3, ...., F102
。 我尝试使用 df.columns 但没有成功地以这种方式重命名它们。 有什么简单的方法可以自动将所有列名自动重命名为F1 to F102
,而不是单独重命名每个列名?
df.columns=["F"+str(i) for i in range(1, 103)]
笔记:
您可以使用计算出的列数(+ 1) 代替“魔术”数字103
,例如
len(df.columns) + 1
,或df.shape[1] + 1
。(感谢ALollz在他的评论中提供了这个提示。)
一种方法是将其转换为一对列表,并将列名列表转换为循环的索引:
import pandas as pd
d = {'Column A': [1, 2, 3, 4, 5, 4, 3, 2, 1], 'Column B': [1, 2, 3, 4, 5, 4, 3, 2, 1], 'Column c': [1, 2, 3, 4, 5, 4, 3, 2, 1]}
dataFrame = pd.DataFrame(data=d)
cols = list(dataFrame.columns.values) #convert original dataframe into a list containing the values for column name
index = 1 #start at 1
for column in cols:
cols[index-1] = "F"+str(index) #rename the column name based on index
index += 1 #add one to index
vals = dataFrame.values.tolist() #get the values for the rows
newDataFrame = pd.DataFrame(vals, columns=cols) #create a new dataframe containing the new column names and values from rows
print(newDataFrame)
输出:
F1 F2 F3
0 1 1 1
1 2 2 2
2 3 3 3
3 4 4 4
4 5 5 5
5 4 4 4
6 3 3 3
7 2 2 2
8 1 1 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.