如何使用Pandas在同一年合并同一个月的行?

时间:2017-01-18 19:36:48

标签: python pandas

我有一个数据框,其组织如下:

Date           combined_news
2008-09-12     []
2008-09-15     []
...            ...
2016-12-25     []

我想修改此数据框,以便每个特定月份的所有新闻项目都在一行中。

Date           combined_news
2008-09        [], []
2008-10        []
...            ...
2016-12        []

到目前为止,我尝试使用

news_data = news_data.groupby(lambda x: (x.year, x.month))['combined_news'].apply(''.join)

但这给了我 ' int'对象没有属性'年 错误。

2 个答案:

答案 0 :(得分:1)

我建议您确保拥有日期时间索引后使用pandas.TimeGrouper。然后你可以做类似

的事情
news_data.index = news_data.Date
news_data = news_data\.
    groupby(pandas.TimeGrouper('M'))\.
    agg({'combined_news': ''.join})

答案 1 :(得分:1)

考虑数据框news_data

news_data = pd.DataFrame(
    dict(combined_news=[[]] * 100),
    pd.date_range('2016-04-01', periods=100)
)

您可以resample + apply(list) + to_period

n1 = news_data.resample('M').combined_news.apply(list)
n1.index = n1.index.to_period('M')

print(n1)

2016-04    [[], [], [], [], [], [], [], [], [], [], [], [...
2016-05    [[], [], [], [], [], [], [], [], [], [], [], [...
2016-06    [[], [], [], [], [], [], [], [], [], [], [], [...
2016-07                 [[], [], [], [], [], [], [], [], []]
Freq: M, Name: combined_news, dtype: object
相关问题