Unable to truncate pandas dataframe (with date as key) using date as string

I am generating an empty framework with a series of dates as an index. Data will be added to the data frame at a later point.

cbd=pd.date_range(start=pd.datetime(2017,01,02),end=pd.datetime(2017,01,30),period=1)

df = pd.DataFrame(data=None,columns=['Test1','Test2'],index=cbd)

df.head()
           Test1 Test2
2017-01-02   NaN   NaN
2017-01-03   NaN   NaN
2017-01-04   NaN   NaN
2017-01-05   NaN   NaN
2017-01-06   NaN   NaN

Several slicing methods do not seem to work. The following returns a KeyError:

df['2017-01-02']

However, any of the following works:

df['2017-01-02':'2017-01-02']
df.loc['2017-01-02']

What am I missing here? Why doesn't the first slice return a result?

+4
source share
3 answers

Dual behavior []indf[]

  • If you are not using :inside [], then the values ​​inside it will be considered columns.
  • : [], .

?

, . , x, y df[x:y] x d[x] x, y df[[x,y]] ().

:

df = pd.DataFrame(data = [[1,2,3], [1,2,3], [1,2,3]],
                                 index = ['A','B','C'], columns = ['A','B','C'])
print df

:

   A  B  C
A  1  2  3
B  1  2  3
C  1  2  3

, df['B'], :

  • B 1 2 3

                    OR
    
  • B 2 2 2.

, , df['B'] , 'B', , .

df['2017-01-02']?

'2017-01-02', , .

df.loc['2017-01-02']?

.loc[] df.loc[row,column], , , , df.loc[row]

+8

, :

loc:

DF [ '2017-01-02']

- :

KeyError; pandas ( ):

dft['2013-1-15 12:30:00']

, .loc

In [74]: dft.loc['2013-1-15 12:30:00']
Out[74]: 
A    0.193284
Name: 2013-01-15 12:30:00, dtype: float64

df['2017-01-02':'2017-01-02']

:

DataFrame DateTimeIndex. , . .

+4

( ), " ". . :

cbd=pd.date_range(start='2017-01-02',end='2017-01-30',period=1)
df = pd.DataFrame(data=None,columns=['Test1','Test2'],index=cbd)

:

In[1]:

df.head(1)

Out[1]:
          Test1 Test2
2017-01-02  NaN NaN

:

In[2]:    

df['2017-01-02']

Out[2]:

KeyError: '2017-01-02'

column:

In[3]:    

df.columns

Out[3]:

Index(['Test1', 'Test2'], dtype='object')

In[4]:

"Test1":

df['Test1']

NaN .

Out[4]:

2017-01-02    NaN
2017-01-03    NaN
2017-01-04    NaN
2017-01-05    NaN

, , , column, df['2017-01-02':'2017-01-02'].

Pandas docs state" KeyError, pandas ( , ).

, , DataFrame.loc , , :

 In[5]:
df.loc['2017-01-02']

 Out[5]:

Test1    NaN
Test2    NaN
Name: 2017-01-02 00:00:00, dtype: object
+1

Source: https://habr.com/ru/post/1668192/


All Articles