【问题标题】:Can a MultiLabelBinarizer represent counts of values?MultiLabelBinarizer 可以表示值的计数吗?
【发布时间】:2018-10-20 00:01:22
【问题描述】:

假设我们在数据框列中有列表

df['a'][0] = ['earth','mars','earth','moon']
df['a'][1] = ['jupiter','pluto','sun']

有没有办法使用multilabelbinarizer来获取

             earth   mars   moon sun  jupiter  pluto
df['a'][0]     2      1       1   0    0       0    
df['a'][1]     0      0       0   1    1       1   

我想把它翻译成一个庞大的程序代码列表

【问题讨论】:

  • 第一个不要将列表命名为列表

标签: python pandas machine-learning deep-learning keras


【解决方案1】:
import pandas as pd
from sklearn.preprocessing import MultiLabelBinarizer

planet = pd.DataFrame()
planet['planet_group'] = ['group_a', 'group_b']
planet['planet_list'] = [
    ['earth', 'mars', 'earth', 'moon'], ['jupiter', 'pluto', 'sun']]

g_planet = []
l_planet = []

for row in planet.itertuples():
    for i in row.planet_list:
        l_planet.append(i.rstrip())
        g_planet.append(row.planet_group)

data_tuples = list(zip(g_planet, l_planet))
new_planet = pd.DataFrame(data_tuples, columns=['group_name', 'value'])

new_planet['value'] = new_planet['value'].apply(lambda x: [x])
mlb = MultiLabelBinarizer()
finaldf = new_planet.join(pd.DataFrame(mlb.fit_transform(new_planet.pop('value')),
                                       columns=mlb.classes_,
                                       index=new_planet.index))
sumdf = finaldf.groupby('group_name').agg(lambda x: sum(x))

print(sumdf)

输出会是这样的

            earth  jupiter  mars  moon  pluto  sun
group_name                                        
group_a         2        0     1     1      0    0
group_b         0        1     0     0      1    1

我所做的是更改您的数据集,为每个列表添加名称,然后将其转换为包含名称和值的新数据框,其中名称包含相关列表中的一个行星。然后应用到 MultiLableBinarier 后,我们按用户分组,并对里面的值求和。

希望对你有所帮助。

【讨论】:

    猜你喜欢
    • 2019-10-15
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多