Python 3.x 访问数据帧中的第一列
如何访问此数据帧中的第一列? 如果我通过列名('Group11…')引用它,我会得到一个错误“notin index”Python 3.x 访问数据帧中的第一列,python-3.x,pandas,Python 3.x,Pandas,如何访问此数据帧中的第一列? 如果我通过列名('Group11…')引用它,我会得到一个错误“notin index” 您所指的是数据帧的索引。因此,如果您的数据帧被称为df,您可以使用df.index访问索引 否则,如果要将引用为列,则需要在使用之前将其转换为列 可复制示例: 下面是一个可复制的示例,显示了访问索引的两种方法: from StringIO import StringIO import pandas as pd data = """Group11.Primary.Phras
您所指的是数据帧的索引。因此,如果您的数据帧被称为
df
,您可以使用df.index
访问索引
否则,如果要将引用为列,则需要在使用之前将其转换为列
可复制示例:
下面是一个可复制的示例,显示了访问索引的两种方法:
from StringIO import StringIO
import pandas as pd
data = """Group11.Primary.Phrase|count|num_cat
CP|4|4
DA|1|1
FW|7|7
"""
df = pd.read_csv(StringIO(data), sep="|", index_col=0)
print("here's how the dataframe looks like")
print(df.head())
print("here's how to access the index")
print(df.index)
print("if you want to turn the index values into a list")
print(list(df.index))
print("you can also reset_index as a column and access it")
df = df.reset_index()
print(df["Group11.Primary.Phrase"])
运行上述代码,将提供以下输出:
here's how the dataframe looks like
count num_cat
Group11.Primary.Phrase
CP 4 4
DA 1 1
FW 7 7
here's how to access the index
Index([u'CP', u'DA', u'FW'], dtype='object', name=u'Group11.Primary.Phrase')
if you want to turn the index values into a list
['CP', 'DA', 'FW']
you can also reset_index as a column and access it
0 CP
1 DA
2 FW
Name: Group11.Primary.Phrase, dtype: object
下面是数据帧的外观
数猫
组11.Primary.Phrase
CP 4
DA 11
FW 7 7
下面是如何访问索引
索引([u'CP',u'DA',u'FW'],dtype='object',name=u'Group11.Primary.Phrase')
如果要将索引值转换为列表
['CP','DA','FW']
您还可以将_索引重置为列并访问它
0 CP
1 DA
2 FW
名称:Group11.Primary.Phrase,数据类型:object
这里有一个指向文档的链接:在您的情况下,您将索引
df['Group11']
In [9]: df
Out[9]:
A B C D
2000-01-01 0.469112 -0.282863 -1.509059 -1.135632
2000-01-02 1.212112 -0.173215 0.119209 -1.044236
2000-01-03 -0.861849 -2.104569 -0.494929 1.071804
In [12]: df[['A', 'B']]
Out[12]:
A B
2000-01-01 -0.282863 0.469112
2000-01-02 -0.173215 1.212112
2000-01-03 -2.104569 -0.861849
iloc返回基于数字索引的数据,这里是第一列(python 0索引)的所有行
如果要使用列名访问列,可以重置索引,然后按列名访问列。i、 e 如果您有一个数据帧,如 count num_cat Group11.Primary.Phrase CP 4 4 DA 1 1 FW 7 7 输出: 0 CP 1 DA 2 FW 0 CP 1 DA 2 FW
要改进您的问题,请在帖子中复制并粘贴代码,而不是使用图像。。
df = df.reset_index()
df['Group11.Primary.Phrase']
0 CP
1 DA
2 FW