如何访问此数据框中的第一列? 如果我按列名称引用它(' Group11 ...'),我会收到错误'不在索引'。
答案 0 :(得分:2)
您所指的是数据帧的索引。因此,如果您的数据框名为df
,则可以使用df.index
访问索引。
否则,如果要引用列作为列,则需要在使用pandas.DataFrame.reset_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
答案 1 :(得分:1)
iloc基于数字索引返回数据,这里是第一个(python 0索引)列的所有行。
df.iloc[:,0]
答案 2 :(得分:1)
如果要使用列名访问列,则可以通过列名重置索引然后访问列。即
如果你有像
这样的数据框count num_cat Group11.Primary.Phrase CP 4 4 DA 1 1 FW 7 7
然后在按名称访问列时重置索引
df = df.reset_index()
df['Group11.Primary.Phrase']
输出:
0 CP 1 DA 2 FW
答案 3 :(得分:0)
以下是文档的链接:Indexing and Selecting Data在您的情况下,您将索引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