我在使用带有日期索引的 DataFrame 时遇到了很多问题。
from pandas import DataFrame, date_range
# Create a dataframe with dates as your index
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
idx = date_range('1/1/2012', periods=10, freq='MS')
df = DataFrame(data, index=idx, columns=['Revenue'])
df['State'] = ['NY', 'NY', 'NY', 'NY', 'FL', 'FL', 'GA', 'GA', 'FL', 'FL']
In [6]: df
Out[6]:
Revenue State
2012-01-01 1 NY
2012-02-01 2 NY
2012-03-01 3 NY
2012-04-01 4 NY
2012-05-01 5 FL
2012-06-01 6 FL
2012-07-01 7 GA
2012-08-01 8 GA
2012-09-01 9 FL
2012-10-01 10 FL
我正在尝试添加一个以'Mean'
组平均值命名的附加列:
我试过这个,但它不起作用:
df2 = df
df2['Mean'] = df.groupby(['State'])['Revenue'].apply(lambda x: mean(x))
In [9]: df2.head(10)
Out[9]:
Revenue State Mean
2012-01-01 1 NY NaN
2012-02-01 2 NY NaN
2012-03-01 3 NY NaN
2012-04-01 4 NY NaN
2012-05-01 5 FL NaN
2012-06-01 6 FL NaN
2012-07-01 7 GA NaN
2012-08-01 8 GA NaN
2012-09-01 9 FL NaN
2012-10-01 10 FL NaN
但我试图得到:
Revenue State Mean
2012-01-01 1 NY 2.5
2012-02-01 2 NY 2.5
2012-03-01 3 NY 2.5
2012-04-01 4 NY 2.5
2012-05-01 5 FL 7.5
2012-06-01 6 FL 7.5
2012-07-01 7 GA 7.5
2012-08-01 8 GA 7.5
2012-09-01 9 FL 7.5
2012-10-01 10 FL 7.5
我怎样才能得到这个数据框?