【问题标题】:table calculation using python [closed]使用python进行表计算[关闭]
【发布时间】:2021-01-11 22:31:22
【问题描述】:

我的数据框看起来像 -

city            state           age
kolkata        west bengal       5
chennai        tamilnadu         7
mumbai         maharashtra       8
chennai        tamilnadu         8

我希望数据框看起来像 -

variable         city_name           count
city               kolkata             1
                   chennai             2
                   mumbai              1
state            west bengal           1
                 tamilnadu             2
                 maharashtra           1
age                  5                 1
                     7                 1
                     8                 2

如何在python中做到这一点?

【问题讨论】:

    标签: python-3.x pandas pandas-groupby


    【解决方案1】:

    我会这样做:

    import pandas as pd
    df = pd.DataFrame(columns=['city', 'state', 'age'])
    df.loc[0] = ['kolkata', 'west bengal', 5]
    df.loc[1] = ['chennai', 'tamilnadu', 7]
    df.loc[2] = ['mumbai', 'maharashtra', 8]
    df.loc[3] = ['chennai', 'tamilnadu', 8]
    
    ct_df = pd.DataFrame(columns=['variable', 'value', 'count'])
    index = 0
    for col in df.columns:
        the-set = set(df[col])
        for element in the_set:
            count = len(df.loc[df[col] == element])
            ct_df.loc[index] = [col, element, count]
            index += 1
    

    结果非常接近你想要的:

      variable        value count
    0     city      chennai     2
    1     city       mumbai     1
    2     city      kolkata     1
    3    state  maharashtra     1
    4    state  west bengal     1
    5    state    tamilnadu     2
    6      age            8     2
    7      age            5     1
    8      age            7     1
    

    【讨论】:

      猜你喜欢
      • 2020-07-08
      • 2020-01-17
      • 2012-04-03
      • 2017-06-14
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 2014-05-25
      • 1970-01-01
      相关资源
      最近更新 更多