如何用n个字母过滤索引并将它们加在一起

时间:2018-02-14 13:59:26

标签: python pandas

这是这个问题的延续。

is there away to output selected columns names from SelectFromModel method?

feature_name = df.columns [feature_idx] 的输出为我提供了许多索引名称。

我的问题是,我怎样才能只显示前3个字母并显示每个字母的总数。

例如

我上面的索引输出是

Index(['banana good', 'banana bad', 'apple good', 'apple bad'])

我希望它显示

ban - 2
app - 2

1 个答案:

答案 0 :(得分:1)

IIUIC,使用

In [199]: idx = pd.Index(['banana good', 'banana bad', 'apple good', 'apple bad'])

In [200]: idx.str[:3].to_series().value_counts()
Out[200]:
app    2
ban    2
dtype: int64