Копирование значений столбца между диапазонами индекса не работает - PullRequest
1 голос
/ 04 апреля 2019

Я пытаюсь преобразовать значения в двух измерениях в Excel в одно измерение, добавляя столбцы один под другим.Однако этот скрипт не добавляет значения в определенный диапазон строк.

Я использую панды для этого.Файл Excel находится здесь: https://drive.google.com/file/d/1dfsfJhLFoGiO8_FG4kmZ87JxT2XFBpvX/view?usp=sharing

import pandas as pd  

inpExcelFile = 'C:/sample.xlsx'
gridCells = pd.read_excel(inpExcelFile, sheetname='Sheet1')
Filter=pd.DataFrame()

for i in range(1938, 1940, 1):
    gridCells_filter = gridCells[gridCells['Year']==i]
    gridCells_filter=gridCells_filter.reset_index(drop=True)
    gridCells_filter.replace(to_replace =",", value =".") 

    #BELOW IS COPYING COLUMN 
    Filter.at[0:30,'Filtered '+str(i)]=gridCells_filter.loc[0:30,'JAN']
    #AFTER THIS, IT DOESNT COPY COLUMN VALUES
    Filter.at[31:61,'Filtered '+str(i)]=gridCells_filter.loc[0:30,'FEB']
    Filter.at[62:92,'Filtered '+str(i)]=gridCells_filter.loc[0:30,'MAR']
    Filter.at[93:123,'Filtered '+str(i)]=gridCells_filter.loc[:30,'APR']
    Filter.at[124:154,'Filtered '+str(i)]=gridCells_filter.loc[0:30,'MAY'] 
    Filter.loc[155:185,'Filtered '+str(i)]=gridCells_filter.loc[0:30,'JUN']
    Filter.at[186:216,'Filtered '+str(i)]=gridCells_filter.loc[0:30,'JUL']
    Filter.at[217:247,'Filtered '+str(i)]=gridCells_filter.loc[0:30,'AUG']
    Filter.at[248:278,'Filtered '+str(i)]=gridCells_filter.loc[0:30,'SEP']
    Filter.at[279:309,'Filtered '+str(i)]=gridCells_filter.loc[0:30,'OCT']
    Filter.at[310:340,'Filtered '+str(i)]=gridCells_filter.loc[0:30,'NOV']
    Filter.at[341:371,'Filtered '+str(i)]=gridCells_filter.loc[0:30,'DEC']
    Filter[Filter.Filtered +str(i) != '-----']

Ожидаемый результат заключается в том, что все значения столбцов должны находиться в одном столбце в нужном порядке.

1 Ответ

1 голос
/ 04 апреля 2019

Вы можете использовать общее решение для всех лет - изменить его на DataFrame.melt и использовать to_datetime с DataFrame.pop для столбцов извлечения, последней сортировки на DataFrame.sort_values и удалите неправильные даты, такие как 30.2.1938 на DataFrame.dropna:

df = pd.read_excel('sample.xlsx', decimal=',')
df = df.melt(['DAY','Year'], value_name='val')

s = df.pop('DAY').astype(str) + df.pop('variable') + df.pop('Year').astype(str)
df['datetime'] = pd.to_datetime(s, format='%d%b%Y', errors='coerce')
df = df.sort_values('datetime').dropna(subset=['datetime'])
     val   datetime
279  --- 1938-01-01
280  --- 1938-01-02
281  --- 1938-01-03
282  --- 1938-01-04
283  --- 1938-01-05
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...