gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:05:46 25 4
gpt4 key购买 nike

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 中读取数据时,它会自动将 2nd 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com