简体   繁体   English

如何在 pandas dataframe 的表中获取所有列名称及其索引号?

[英]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.

相关问题 使用索引号同时更改 pandas 数据框中的多个列名(并非所有列名) - Change multiple column names in pandas dataframe (not all colmn names) at the same time using index numbers 如何在pandas DataFrame中选择名称以X开头的所有列 - How to select all columns whose names start with X in a pandas DataFrame 如何在大型 pandas dataframe 上显示所有列的名称? - How to show all columns' names on a large pandas dataframe? Python Pandas:如何从数据帧的索引中获取行名? - Python Pandas: How to get the row names from index of a dataframe? 如果另一个 dataframe 中没有具有相同索引和列名的值,如何清除 pandas 中 dataframe 的列中的值 - How to clear values in columns of a dataframe in pandas if there are no values in another dataframe with the same index an column names 按熊猫数据框的索引对所有列的值进行分组 - Grouping the values of all columns by index of a pandas dataframe 当列名是整数时,按列号索引 Pandas DataFrame - Index pandas DataFrame by column numbers, when column names are integers 如何获取数据框中所有重复项的索引(pandas-python) - How to get index for all the duplicates in a dataframe (pandas - python) 如何在pandas python中获取数据框中三列的所有组合> - How to get all combinations of three columns in a dataframe in pandas python> 为列分配名称后,如何通过其数字索引在 Pandas dataframe 中打印一行? - How to print a row in Pandas dataframe by its numerical index after assigning names to columns?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM