pandas取第一行数据_Pandas-获取给定列的第一行值

要选择ith行,use ^{}:In [31]: df_test.iloc[0]

Out[31]:

ATime 1.2

X 2.0

Y 15.0

Z 2.0

Btime 1.2

C 12.0

D 25.0

E 12.0

Name: 0, dtype: float64

要选择Btime列中的第i个值,可以使用:In [30]: df_test['Btime'].iloc[0]

Out[30]: 1.2

df_test['Btime'].iloc[0](推荐)和df_test.iloc[0]['Btime']之间存在差异:

数据帧将数据存储在基于列的块中(其中每个块有一个

数据类型)。如果首先选择按列,则可以返回视图(即

比返回副本快)并且保留原始数据类型。相反,

如果您首先选择“按行”,并且如果数据帧具有不同的列

数据类型,然后Pandas将数据复制到一系列新的对象数据类型中。所以

选择列比选择行快一点。因此,尽管

df_test.iloc[0]['Btime']工作,df_test['Btime'].iloc[0]有点

更有效率。

在作业方面,两者有很大的区别。

df_test['Btime'].iloc[0] = x影响df_test,但是df_test.iloc[0]['Btime']

可能不会。有关原因的解释,请参见下文。因为

索引顺序对行为有很大影响,最好使用单个索引分配:df.iloc[0, df.columns.get_loc('Btime')] = x

df.iloc[0, df.columns.get_loc('Btime')] = x(推荐):df.loc[df.index[n], 'Btime'] = x

或者df.iloc[n, df.columns.get_loc('Btime')] = x

后一种方法要快一点,因为df.loc必须将行和列标签转换为

位置索引,因此如果使用

df.iloc取而代之。

df['Btime'].iloc[0] = x有效,但不建议:

尽管这样做有效,但它利用了当前实现数据帧的方式。不能保证熊猫将来一定要这样工作。特别是,它利用了这样一个事实,即(当前)df['Btime']总是返回

查看(不是副本),因此df['Btime'].iloc[n] = x可用于分配一个新值

在df的Btime列的第n个位置。

由于Pandas没有明确保证索引器何时返回视图和副本,因此使用链式索引的赋值通常都会引发一个SettingWithCopyWarning,即使在这种情况下,赋值成功地修改了df:In [22]: df = pd.DataFrame({'foo':list('ABC')}, index=[0,2,1])

In [24]: df['bar'] = 100

In [25]: df['bar'].iloc[0] = 99

/home/unutbu/data/binky/bin/ipython:1: SettingWithCopyWarning:

A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

self._setitem_with_indexer(indexer, value)

In [26]: df

Out[26]:

foo bar

0 A 99

2 B 100

1 C 100

df.iloc[0]['Btime'] = x不工作:

相反,使用df.iloc[0]['bar'] = 123的赋值不起作用,因为df.iloc[0]正在返回一个副本:In [66]: df.iloc[0]['bar'] = 123

/home/unutbu/data/binky/bin/ipython:1: SettingWithCopyWarning:

A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

In [67]: df

Out[67]:

foo bar

0 A 99

2 B 100

1 C 100

警告:我以前建议过df_test.ix[i, 'Btime']。但这并不能保证给您提供ith值,因为ix在尝试通过位置索引之前,尝试通过标签索引。因此,如果数据帧有一个整数索引,该索引的排序顺序不是从0开始的,那么使用ix[i]将返回标记为i的行,而不是ith的行。例如In [1]: df = pd.DataFrame({'foo':list('ABC')}, index=[0,2,1])

In [2]: df

Out[2]:

foo

0 A

2 B

1 C

In [4]: df.ix[1, 'foo']

Out[4]: 'C'

你可能感兴趣的:(pandas取第一行数据)