在索引范围之间复制列值不起作用

时间:2019-04-04 04:40:13

标签: pandas dataframe

我试图将excel中2维的值转换为一个维,在另一维下添加一列。但是,此脚本不会将值添加到特定的行范围。

我正在用熊猫来做到这一点。 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 个答案:

答案 0 :(得分:1)

您可以使用所有年份的通用解决方案-通过DataFrame.melt进行整形,并使用to_datetimeDataFrame.pop来提取列,最后使用DataFrame.sort_values进行排序,并删除错误的日期时间,例如{由DataFrame.dropna的{1}}:

30.2.1938