现在我在 Pandas 中有一个大型数据框,我想做的是根据一个指标制作一组较小的组。然后将迭代这些组以创建排列。这有点复杂,但这里有一个例子:
数据框
KW POS
Cat Noun
in Prep
the Prep
Brown Adj
hat Noun
我正在尝试做的现在是像这样基于 POS 创建 3 个组
KW POS KW POS KW POS
Cat Noun in Prep Brown Adj
hat Noun Prep Prep
但是,我认为它们需要是唯一组的原因是这些组将被迭代以创建单词排列——即第 1 组中的一个词、第 2 组中的一个词、第 3 组中的一个词。
问题是 1.) 像下面这样的分组方法是否适合从中创建排列?
group = newlist.groupby(['POS'])
2.) 如果不是,我如何创建适合迭代的不同的较小数据框?
请您参考如下方法:
迭代 groupby(或 SeriesGroupby)产生键和来自该组的子帧/系列:
In [11]: {k: v for (k, v) in g['KW']} # equivalently/cryptically: dict(iter(g['KW']))
Out[11]:
{'Adj': 3 Brown
Name: KW, dtype: object,
'Noun': 0 Cat
4 hat
Name: KW, dtype: object,
'Prep': 1 in
2 the
Name: KW, dtype: object}
IIUYC 可能会考虑使用 pandas 的 cartesian_product(有点隐藏......):
In [12]: pd.tools.util.cartesian_product(res.values())
Out[12]:
[array(['Cat', 'Cat', 'hat', 'hat'], dtype=object),
array(['Brown', 'Brown', 'Brown', 'Brown'], dtype=object),
array(['in', 'the', 'in', 'the'], dtype=object)]
然后像 map、zip、join 组合应该得到你想要的东西(?):
In [13]: map(' '.join, zip(*_))
Out[13]: ['Cat Brown in', 'Cat Brown the', 'hat Brown in', 'hat Brown the']
