In [1]: dates = pd.date_range('1/1/2000', periods=8)
In [2]: df = pd.DataFrame(np.random.randn(8, 4), index=dates, columns=['A', 'B', 'C', 'D'])
In [3]: s = df['A']
2.10 Fast scalar value getting and setting
Since indexing with [] must handle a lot of cases (single-label access,
slicing, boolean indexing, etc.), it has a bit of overhead in order to figure
out what you’re asking for. If you only want to access a scalar value, the
fastest way is to use the at and iat methods, which are implemented on
all of the data structures.
Similarly to loc, at provides label based scalar lookups, while, iat provides integer based lookups analogously to iloc
In [4]: s
Out[4]:
2000-01-01 0.4691
2000-01-02 1.2121
2000-01-03 -0.8618
2000-01-04 0.7216
2000-01-05 -0.4250
2000-01-06 -0.6737
2000-01-07 0.4047
2000-01-08 -0.3706
Freq: D, Name: A, dtype: float64
In [5]: s.iat[5]
Out[5]: -0.67368970808837059
In [6]: df
Out[6]:
A B C D
2000-01-01 0.4691 -0.2829 -1.5091 -1.1356
2000-01-02 1.2121 -0.1732 0.1192 -1.0442
2000-01-03 -0.8618 -2.1046 -0.4949 1.0718
2000-01-04 0.7216 -0.7068 -1.0396 0.2719
2000-01-05 -0.4250 0.5670 0.2762 -1.0874
2000-01-06 -0.6737 0.1136 -1.4784 0.5250
2000-01-07 0.4047 0.5770 -1.7150 -1.0393
2000-01-08 -0.3706 -1.1579 -1.3443 0.8449
In [7]: dates
Out[7]:
DatetimeIndex(['2000-01-01', '2000-01-02', '2000-01-03', '2000-01-04',
'2000-01-05', '2000-01-06', '2000-01-07', '2000-01-08'],
dtype='datetime64[ns]', freq='D')
In [8]: df.at[dates[5], 'A']
Out[8]: -0.67368970808837059
In [9]: df.iat[3, 0]
Out[9]: 0.72155516224436689
You can also set using these same indexers.
In [10]: df
Out[10]:
A B C D
2000-01-01 0.4691 -0.2829 -1.5091 -1.1356
2000-01-02 1.2121 -0.1732 0.1192 -1.0442
2000-01-03 -0.8618 -2.1046 -0.4949 1.0718
2000-01-04 0.7216 -0.7068 -1.0396 0.2719
2000-01-05 -0.4250 0.5670 0.2762 -1.0874
2000-01-06 -0.6737 0.1136 -1.4784 0.5250
2000-01-07 0.4047 0.5770 -1.7150 -1.0393
2000-01-08 -0.3706 -1.1579 -1.3443 0.8449
In [11]: df.at[dates[5], 'E'] = 7
In [12]: df.iat[3, 0] = 7
at may enlarge the object in-place as above if the indexer is missing.
In [13]: df
Out[13]:
A B C D E
2000-01-01 0.4691 -0.2829 -1.5091 -1.1356 NaN
2000-01-02 1.2121 -0.1732 0.1192 -1.0442 NaN
2000-01-03 -0.8618 -2.1046 -0.4949 1.0718 NaN
2000-01-04 7.0000 -0.7068 -1.0396 0.2719 NaN
2000-01-05 -0.4250 0.5670 0.2762 -1.0874 NaN
2000-01-06 -0.6737 0.1136 -1.4784 0.5250 7.0
2000-01-07 0.4047 0.5770 -1.7150 -1.0393 NaN
2000-01-08 -0.3706 -1.1579 -1.3443 0.8449 NaN
In [14]: df.at[dates[-1]+1, 0] = 7
In [15]: df
Out[15]:
A B C D E 0
2000-01-01 0.4691 -0.2829 -1.5091 -1.1356 NaN NaN
2000-01-02 1.2121 -0.1732 0.1192 -1.0442 NaN NaN
2000-01-03 -0.8618 -2.1046 -0.4949 1.0718 NaN NaN
2000-01-04 7.0000 -0.7068 -1.0396 0.2719 NaN NaN
... ... ... ... ... ... ...
2000-01-06 -0.6737 0.1136 -1.4784 0.5250 7.0 NaN
2000-01-07 0.4047 0.5770 -1.7150 -1.0393 NaN NaN
2000-01-08 -0.3706 -1.1579 -1.3443 0.8449 NaN NaN
2000-01-09 NaN NaN NaN NaN NaN 7.0
[9 rows x 6 columns]