我在三列上运行简单的平均操作。我正在将月度数据转换为季度平均值。数据如下所示:
2000.1 2000.2 2000.3....
18 15 27
我想将其转换为
2000.q1
20
这是我到目前为止所做的:
def convert_housing_data_to_quarters(): '''将住房数据转换为季度并将其作为均值返回 数据框中的值。此数据框应为数据框 2000q1到2016q3的列,应该有一个多索引 形状为[“State”,“RegionName”]。
Note: Quarters are defined in the assignment description, they are
not arbitrary three month periods.
The resulting dataframe should have 67 columns, and 10,730 rows.
'''
# read in the zillow housing data
zillow_df = pd.read_csv('City_Zhvi_AllHomes.csv')
print(zillow_df.iloc[1,1])
print(len(zillow_df))
# slice from 2000q1 to 2016q3
print(zillow_df.columns)
print(zillow_df.columns[6:51])
zillow_df.drop(zillow_df.columns[6:51],axis=1,inplace=True)
# generate quarterly average
y = 2000
q = 1
for i in range(67):
y_q = str(y)+'q'+str(q)
#print(y_q)
print(zillow_df.columns[6+(i)*3])
print(zillow_df[zillow_df.columns[6+(i)*3]])
zillow_df[y_q]=(zillow_df[zillow_df.columns[6+(i)*3]]+zillow_df[zillow_df.columns[6+1+(i)*3]]+zillow_df[zillow_df.columns[6+2+(i)*3]])/3
q=q+1
if q==5:
q=1
y=y+1
return zillow_df.head()
我认为我的代码是正确的,但每次我在ipython笔记本中运行它。它说内核死了。我不知道为什么。
答案 0 :(得分:0)
我认为您需要先将to_datetime
列转换为to_period
,然后再转换为month period
。
然后quarters
mean
和axis=1
汇总df.columns = pd.to_datetime(df.columns, format='%Y.%m').to_period('m')
print (df)
2000-01 2000-02 2000-03
0 18 15 27
df = df.resample('Q', axis=1).mean()
df.columns = df.columns.strftime('%Y.q%q')
print (df)
2000.q1
0 20
是按列名聚合的。)
按格式将resample
的最后一列转换为字符串:
public static void main(String[] args) throws IOException {
FileReader in = new FileReader("C:\\Users\\itmaint\\eclipse-workspace\\IO\\src\\IO\\file1.txt");
int times=0;
int c;
while ((c = in.read()) != -1) {
System.out.println("Reading using Reader");
times++;
System.out.println("'"+(char)c+"'"+" : "+c+" ");
}
System.out.println("times ="+times);
in.close();
times=0;
FileInputStream in1= new FileInputStream("C:\\Users\\itmaint\\eclipse-workspace\\IO\\src\\IO\\file1.txt");
while((c=in1.read())!=-1)// reads a byte of data
{
System.out.println("Reading using Stream");
times++;
System.out.println("'"+(char)c+"'"+" : "+c+" ");
}
System.out.println("times ="+times);
in1.close();
}