[英]How to get all columns names with their index numbers in a table of a pandas dataframe?
I would like to remove certain columns of a dataframe and found it annoying typing all the column names.我想删除 dataframe 的某些列,发现输入所有列名很烦人。 I would like to use columns index numbers instead of columns to remove the columns from the dataframe.我想使用列索引号而不是列来从 dataframe 中删除列。 The following code gives all the header names but how to get index numbers too?以下代码给出了所有 header 名称,但如何获取索引号呢?
import pandas as pd
df=pd.read_csv("https://raw.githubusercontent.com/codebasics/py/master/ML/14_naive_bayes/titanic.csv")
print(df.columns)
Expected Output:预期 Output:
'PassengerId', 0
'Name', 1
'Pclass', 2
'Sex', 3
'Age', 4
'SibSp', 5
'Parch', 6
'Ticket', 7
'Fare', 8
'Cabin', 9
'Embarked', 10
'Survived', 11
Use pd.Series
with columns names:将pd.Series
与列名一起使用:
s = pd.Series(df.columns)
print (s)
0 PassengerId
1 Name
2 Pclass
3 Sex
4 Age
5 SibSp
6 Parch
7 Ticket
8 Fare
9 Cabin
10 Embarked
11 Survived
dtype: object
Like mentioned @timgeb (thank you) is possible select by positions instead columns names:就像提到的@timgeb(谢谢)是可能的 select 通过位置而不是列名:
df['Name']
df.iloc[:, 1]
If need remove first 2 columns use:如果需要删除前 2 列,请使用:
df = df.iloc[:, 2:]
To print both index number and column name you can use enumerate
:要打印索引号和列名,您可以使用enumerate
:
>>> list(enumerate(df.columns))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.