python - 如何删除从pandas中的excel读取的重复列

标签 python excel python-3.x pandas

Excel 中的数据:

a   b   a   d
1   2   3   4
2   3   4   5
3   4   5   6
4   5   6   7

代码:

df= pd.io.excel.read_excel(r"sample.xlsx",sheetname="Sheet1")
df
   a  b  a.1  d
0  1  2    3  4
1  2  3    4  5
2  3  4    5  6
3  4  5    6  7

如何删除列a.1

当pandas从excel读取数据时,它会自动将第二个a的列名更改为a.1。

我尝试了 df.drop("a.1",index=1) ,这不起作用。

我有一个巨大的 Excel 文件,其中有重复的名称,而且我只对其中的几列感兴趣。

最佳答案

您需要为drop传递axis=1上类:

In [100]:
df.drop('a.1', axis=1)

Out[100]:
   a  b  d
0  1  2  4
1  2  3  5
2  3  4  6
3  4  5  7

或者只是传递感兴趣的列列表以进行列选择:

In [102]:
cols = ['a','b','d']
df[cols]

Out[102]:
   a  b  d
0  1  2  4
1  2  3  5
2  3  4  6
3  4  5  7

也适用于“花式索引”:

In [103]:
df.ix[:,cols]

Out[103]:
   a  b  d
0  1  2  4
1  2  3  5
2  3  4  6
3  4  5  7

关于python - 如何删除从pandas中的excel读取的重复列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30528840/

相关文章:

python - 在 Xcode 中运行 iOS 项目之前运行 python HttpServer

python - 修复 "Binary period"的解决方案

excel - 上传后的 VBA Sharepoint checkin 文件

输入左括号时 Excel 崩溃

python - 恢复 Latex 编译错误

python - 如何在列表循环中找到特定位置的最小值和最大值?

python - 在 Windows 10 上的 Anaconda 上安装 Graphlab create(Python、机器学习)

python - 如何在Python中正确下载股票数据

windows - 构建 MFC 自动化示例(使用 OLE 自动化访问 Excel)。无法编译

python - 类型错误 : unsupported operand type(s) for/: 'Image' and 'int'