【发布时间】:2019-12-31 01:46:35
【问题描述】:
我在 pandas 数据框中有一个数据表,其中每年为行,每个月为列。
0 Year Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
1 1876 11.3 11.0 0.2 9.4 6.8 17.2 -5.6 12.3 10.5 -8.0 -2.7 -3.0
2 1877 -9.7 -6.5 -4.7 -9.6 3.6 -16.8 -10.2 -8.2 -17.2 -16.0 -12.6 -12.6
3 1878 -8.7 -21.1 -15.5 -8.8 2.1 -3.1 15.9 13.0 17.7 10.9 15.1 17.9
4 1879 12.7 14.3 13.2 12.7 2.1 16.4 21.8 22.6 18.9 15.2 9.8 -5.5
5 1880 10.8 7.7 14.3 5.3 12.3 9.1 1.6 14.3 8.1 4.8 7.2 -1.9
我希望转置数据以保留年份作为一列,添加月份作为一列
我已经尝试过融化和旋转,但还不够。
import urllib.request as request
from contextlib import closing
import shutil
import pandas as pd
from datetime import datetime
import pickle
def prepare_enso_data():
""" get the raw enso data and prepare for use in bokeh figures
elsewhere.
"""
# get latest data from bom website
with closing(request.urlopen('ftp://ftp.bom.gov.au/anon/home/ncc/www/sco/soi/soiplaintext.html')) as r:
with open('.\\enso\\data\\enso_bom_historical.txt', 'wb') as enso_file:
shutil.copyfileobj(r, enso_file)
# now strip unwanted html
with open('.\\enso\\data\\enso_bom_historical.txt', 'r') as enso_file:
for i in range(11):
next(enso_file)
# remove unwanted characters and html at end of file
enso_list = [
x.replace('b','').replace('\n','').replace('Fe', "Feb").split() for x in enso_file if '<' not in x]
enso_df = pd.DataFrame(enso_list)
# set the first row as column names
header = enso_df.loc[0]
enso_df = enso_df[1:]
enso_df.columns = header
print(enso_df.head())
enso_df_m = enso_df.melt(
id_vars=['Year'],
# value_vars=[],
var_name='Month')
我希望它看起来像这样:
0 Year Month Value
1 1876 Jan 11.3
2 1876 Feb 11
3 1876 Mar 0.2
4 1876 Apr 9.4
5 1876 May 6.8
6 1876 Jun 17.2
7 1876 Jul -5.6
8 1876 Aug 12.3
9 1876 Sep 10.5
10 1876 Oct -8
11 1876 Nov -2.7
12 1876 Dec -3
【问题讨论】:
-
df.melt('year')??