[英]Change multiple column names in pandas dataframe (not all colmn names) at the same time using index numbers
[英]How to get all columns names with their index numbers in a table of a pandas dataframe?
我想删除 dataframe 的某些列,发现输入所有列名很烦人。 我想使用列索引号而不是列来从 dataframe 中删除列。 以下代码给出了所有 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)
预期 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
将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
就像提到的@timgeb(谢谢)是可能的 select 通过位置而不是列名:
df['Name']
df.iloc[:, 1]
如果需要删除前 2 列,请使用:
df = df.iloc[:, 2:]
要打印索引号和列名,您可以使用enumerate
:
>>> list(enumerate(df.columns))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.