【问题标题】:Making pandas dataframe from dict从 dict 制作 pandas 数据框
【发布时间】:2019-08-12 14:18:29
【问题描述】:

我正在执行一项任务,其中我以政党为键,政党成员的性别为项目。

字典被命名为:genderlist。我的字典代码如下:

soup = BeautifulSoup(open(loadKandidatenlijst()).read(), features="xml")

genderlist = {}

for affiliation in soup.findAll('Affiliation'):
    genders = []
    party = affiliation.RegisteredName.text
    genderlist[party] = 0
    for name in affiliation.findAll('Candidate'):
        gender = name.Gender.text
        genders.append(gender)
        genderlist[party] = genders

genderlist['Partij van de Arbeid (P.v.d.A.)'][:6], len(genderlist), len(genderlist['CDA'])

我的输出结果为:(['male', 'female', 'male', 'female', 'male', 'female'], 24, 50)

所以,当我插入派对名称时,它会导致派对中所有成员的性别。

现在我需要制作一个这样的数据框:

因此,它分别计算性别并返回数据框中的女性百分比。

我现在已经尝试过了:

pd.DataFrame(genderlist.items(),columns=['male', 'female'])

结果:

我怎样才能像预期的那样制作一个数据框,其中将计算党的前 30 名候选人并产生一个具有百分比的男性和女性分开的数据框?

你能帮帮我吗,从现在开始我可以用我的代码做什么。

提前谢谢你

【问题讨论】:

    标签: python pandas dataframe dictionary data-science


    【解决方案1】:

    df 成为您当前的输出(我更改了列名):

    df = pd.DataFrame(genderlist.items(), columns=['party_name', 'gender_list'])
    

    gender_list 现在是这种格式的列表列:

    ['male', 'female', 'male', 'female', 'male', 'female']
    

    现在您可以使用 Counter 应用唯一的元素计数,这将返回一个字典,然后使用 apply(pd.Series) 将字典列拆分为单独的列。

    from collections import Counter
    df['gender_list'].apply(Counter).apply(pd.Series)
    

    【讨论】:

      【解决方案2】:

      您可以将list.count(element) 函数与python 字典理解一起使用,首先创建一个包含您需要的数据的gender_counts 字典,然后使用df.from_dict 将其转换为数据帧

      #each list has gender of members of that party
      party_A
      ['female', 'female', 'male', 'female', 'male', 'male', 'female', 'female',
       'female', 'female']
      
      gender_dict = {'Party_A': party_A, 'Party_B': party_B, 
                     'Party_C': party_C, 'Party_D': party_D}
      
      gender_counts = {k: [v.count('male'), v.count('female')] for k, v in gender_dict.items()}
      
      gender_counts
      {'Party_A': [3, 7],
       'Party_B': [5, 9],
       'Party_C': [13, 7],
       'Party_D': [9, 6]}
      
      df = pd.DataFrame.from_dict(gender_counts, orient='index', columns=['male', 'female'])
      
      df
           male female 
      Party_A 3   7   
      Party_B 5   9   
      Party_C 13  7   
      Party_D 9   6   
      
      
      df['Women_pecentage'] = df.female/(df.male+df.female)
      
      df.round(2)
      
           male female Women_Percentage
      Party_A 3   7   0.70
      Party_B 5   9   0.64
      Party_C 13  7   0.35
      Party_D 9   6   0.40
      

      【讨论】:

        猜你喜欢
        • 2018-12-02
        • 2016-12-20
        • 2021-04-22
        • 2016-11-22
        • 2017-05-02
        • 1970-01-01
        • 2017-03-05
        • 1970-01-01
        • 2021-07-17
        相关资源
        最近更新 更多