2015-09-24 2 views
1

Мне не нравится думать, сколько времени я потратил на попытку исправить эту тривиальную проблему, но я пытаюсь преобразовать строку в дату для каждой строки в определенном столбце. Ниже мой кадр данных:Строка во времени, использующая для цикла в кадре данных

table: 
     day date   rankgross_budget 
    0 Fri Sep. 18, 2015 5 $2,298,380 
    1 Sat Sep. 19, 2015 5 $2,993,960 
    2 Sun Sep. 20, 2015 5 $1,929,695 
    3 Mon Sep. 21, 2015 5 $617,410 
    4 Tue Sep. 22, 2015 5 $851,220 

Моя неудачная попытка изменить дату в формате даты идет как так:

for d in table.date : 
     table.date[d] = time.strptime(table.date[d],'%b. %d, %Y') 

И я получаю бросил эту ошибку:

TypeError         Traceback (most recent call last) 
pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:3704)() 

pandas/hashtable.pyx in pandas.hashtable.Int64HashTable.get_item (pandas/hashtable.c:7200)() 

TypeError: an integer is required 

During handling of the above exception, another exception occurred: 

KeyError         Traceback (most recent call last) 
<ipython-input-8-cc64c6038ec8> in <module>() 
    21 
    22 for d in table.date : 
---> 23   table.date[d] = time.strptime(table.date[d],'%b. %d, %Y') 
    24 
    25 table.head() 

/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/pandas/core/series.py in __getitem__(self, key) 
    519  def __getitem__(self, key): 
    520   try: 
--> 521    result = self.index.get_value(self, key) 
    522 
    523    if not np.isscalar(result): 

/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/pandas/core/index.py in get_value(self, series, key) 
    1593 
    1594   try: 
-> 1595    return self._engine.get_value(s, k) 
    1596   except KeyError as e1: 
    1597    if len(self) > 0 and self.inferred_type in ['integer','boolean']: 

pandas/index.pyx in pandas.index.IndexEngine.get_value (pandas/index.c:3113)() 

pandas/index.pyx in pandas.index.IndexEngine.get_value (pandas/index.c:2844)() 

pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:3761)() 

KeyError: 'Sep. 18, 2015' 

Где я иду не так? Любая помощь по этому поводу была бы очень благодарна :)

ответ

1

Вы пытаетесь получить доступ к значению с помощью table.date[d], который не имеет индекса значения 'Sep. 18, 2015', следовательно KeyError. Печать table.date колонки вы увидите, что это то, что он выглядит следующим образом:

In [19]: df.date 
Out[19]: 
0 Sep. 18, 2015 
1 Sep. 19, 2015 
Name: date, dtype: object 

Обычно следует использовать метод apply(), чтобы сделать это, apply() принимает функцию в качестве аргумента и применяет его к колонку вы определяете:

# Create the function that transforms the string. 
to_time = lambda x: time.strptime(x,'%b. %d, %Y') 

# Pass it to apply for the column "date". 
table["date"] = table["date"].apply(to_time) 

Для фиктивных данных результат:

Out[17]: 
0 (2015, 9, 18, 0, 0, 0, 4, 261, -1) 
1 (2015, 9, 19, 0, 0, 0, 5, 262, -1) 
Name: date, dtype: object 
1

Один простой вариант - использовать to_datetime().

df['date'] = pd.to_datetime(df['date']) 

дает вам:

df['date'] 
0 2015-09-18 
1 2015-09-19 
2 2015-09-20 
3 2015-09-21 
4 2015-09-22 
Name: date, dtype: datetime64[ns] 
+0

Это именно то, что я был после. Должен прочитать документацию более подробно для панд. Cheers rurp –

Смежные вопросы