[英]Parsing Excel data with pandas - why is it skipping columns when renaming columns?
#dataframe have default columns names
df = pd.DataFrame({0:list('abcdef'),
1:[4,5,4,5,5,4],
2:[7,8,9,4,2,3]})
print (df)
0 1 2
0 a 4 7
1 b 5 8
2 c 4 9
3 d 5 4
4 e 5 2
5 f 4 3
#first column called index
print (df.index)
RangeIndex(start=0, stop=6, step=1)
#check columns names (RangeIndex can be also)
print (df.columns)
Int64Index([0, 1, 2], dtype='int64')
#add 1 to columns anmes and convert to str
df.columns = (df.columns + 1).astype(str)
print (df)
1 2 3
0 a 4 7
1 b 5 8
2 c 4 9
3 d 5 4
4 e 5 2
5 f 4 3
print (df.columns)
Index(['1', '2', '3'], dtype='object')
变更列名的另一个解决方案是rename
:
df = df.rename(columns = lambda x: str(x + 1))
print (df.columns)
Index(['1', '2', '3'], dtype='object')
如果要创建1,2,3..N
范围字符串列:
df = pd.DataFrame({'a':list('abcdef'),
'f':[4,5,4,5,5,4],
'm':[7,8,9,4,2,3]})
print (df)
a f m
0 a 4 7
1 b 5 8
2 c 4 9
3 d 5 4
4 e 5 2
5 f 4 3
df.columns = pd.RangeIndex(1, df.shape[1] + 1).astype(str)
print (df.columns)
Index(['1', '2', '3'], dtype='object')
print (df)
1 2 3
0 a 4 7
1 b 5 8
2 c 4 9
3 d 5 4
4 e 5 2
5 f 4 3
这是python和excel的教程:
https://github.com/python-excel/tutorial/raw/master/python-excel.pdf
第10页和第11页介绍了如何对行和列进行切片。 浏览文档时,还有更多选项。
GitHub页面
https://github.com/python-excel/tutorial
另一种选择是删除
https://docs.aspose.com/display/cellsjava/Inserting+and+Deleting+Rows+and+Columns+in+Python
我希望这有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.