繁体   English   中英

用Pandas解析Excel数据-为什么在重命名列时跳过列?

[英]Parsing Excel data with pandas - why is it skipping columns when renaming columns?

我真的希望它简单易用。 我正在使用python熊猫在excel工作簿中阅读。 当我将列重命名为数字1:len(columns)时,它将跳过前几列。

似乎仅在单元格中没有值时才跳过它们。 即使该列没有值,我仍然希望它为它们编号1,2,3 ...

xl = pd.ExcelFile('Excel.xlsm')
df = xl.parse('Worksheet1')
df.columns = [str(x) for x in range(0,df.shape[1])]

我希望有人能指出我正确的方向。 我尝试使用标题跳过前几列,但没有任何结果给我带来一致而可靠的结果。 谢谢!

这是我通过跳过列获得的输出。

#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.

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