【发布时间】:2018-09-10 04:17:09
【问题描述】:
我在 pandas 中有一个看起来像这样的数据框
Year Month Month_index Rainfall
1900 Jan 1 4.8
1901 Jan 1 5
.
.
.
1900 Feb 2 3.2
1901 Feb 2 4.3
.
.
要使用日期时间索引,我需要重新排列它以使其看起来像 -
Year Month Month_index Rainfall
1900 Jan 1 4.8
1900 Feb 2 3.2
.
.
1901 Jan 1 5
1901 Feb 2 4.3
.
.
当然,为了简洁起见,我只是展示了完整的 12 个月。我对python相当陌生,所以我不知道是否有一个命令可以做到这一点。 先感谢您!
编辑:这是我迄今为止使用的代码 -
import csv
#import pyexcel-io as pi
import numpy as np
import pandas as pd
import dateutil
#Read data from csv file into dataframe
df =pd.read_csv('/Users/Gingeraffe/Documents/University/3rd_year/Bureau_Research/Notebooks/Data/rainfall_SW_WA.csv')
months = df.columns[1:]
#Melt is putting months down a column and the data down another column.
Problem is ' jan jan jan... feb feb feb..' etc. instead of 'jan feb mar.. etc'
df = pd.melt(df, id_vars='Year', value_vars=months, var_name='Month')
df.insert(2,'Month_index',0)
M = {'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4, 'May':5, 'June':6, 'July':7, 'Aug':8, 'Sep':9, 'Oct':10, 'Nov':11, 'Dec':12}
df.Month_index = df.Month.map(M)
【问题讨论】:
-
欢迎来到 SO。你能更详细地描述你的问题吗?例如。通过添加描述您的问题的代码、命令或屏幕截图。另请查看帮助中心,尤其是asking 和minimal examples。谢谢。
标签: python python-3.x pandas datetime