要选择该
ith行,请使用
iloc:
In [31]: df_test.iloc[0]Out[31]: ATime 1.2X 2.0Y 15.0Z 2.0Btime 1.2C 12.0D 25.0E 12.0Name: 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']
:
Dataframe将数据存储在基于列的块中(每个块具有一个dtype)。如果首先按列选择,则可以返回 视图
(比返回副本要快),并且保留原始dtype。相反,如果首先选择按行,并且Dataframe的列具有不同的dtype,则Pandas将数据 复制
到新的Object dtype系列中。因此,选择列比选择行要快一些。因此,尽管
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')] = xdf.iloc[0, df.columns.get_loc('Btime')] = x (推荐的):
为Dataframe分配新值的 推荐方法
是避免链接索引,而应使用andrew所示的方法,
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
可行,但不建议:
尽管这可行,但它利用了 当前
实现Dataframes的方式。不能保证熊猫将来会以这种方式工作。特别是,它利用了以下事实:(当前)
df['Btime']始终返回视图(而不是副本),因此
df['Btime'].iloc[n]= x可用于在的列的第n个位置 分配 新值。
Btime``df
由于Pandas无法明确保证索引器何时返回视图还是副本,因此使用链式索引的赋值通常会产生,
SettingWithCopyWarning即使在这种情况下,赋值可以成功修改
df:
In [22]: df = pd.Dataframe({'foo':list('ABC')}, index=[0,2,1])In [24]: df['bar'] = 100In [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 DataframeSee 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]: dfOut[26]: foo bar0 A 99 <-- assignment succeeded2 B 1001 C 100df.iloc[0]['Btime'] = x
不起作用:
相比之下,with的分配
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 DataframeSee the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copyIn [67]: dfOut[67]: foo bar0 A 99 <-- assignment failed2 B 1001 C 100
警告 :我之前曾建议过
df_test.ix[i, 'Btime']。但这不能保证为您提供
ith值,因为在尝试按 位置
索引之前先尝试
ix按 标签 索引。因此,如果Dataframe的整数索引不是从0开始的排序顺序,则using将返回 标有标签
的行,而不是该行。例如,
ix[i]
i``ith
In [1]: df = pd.Dataframe({'foo':list('ABC')}, index=[0,2,1])In [2]: dfOut[2]: foo0 A2 B1 CIn [4]: df.ix[1, 'foo']Out[4]: 'C'


