【问题标题】:How to group by the words and create an equivalent column consisting of float values? (Pandas)如何按单词分组并创建由浮点值组成的等效列? (熊猫)
【发布时间】:2021-10-16 13:15:04
【问题描述】:

我有一个数据框:

   Text                 
   Background  
   Clinical      
   Method
   Direct
   Background
   Direct

现在我想根据它们的第一个单词将它们分组到新列中,例如 Background 属于第 1 组 Clinical 属于第 2 组,就像这样。

预期输出:

一个数据框:

   Text            Group      
   Background       1
   Clinical         2
   Method           3
   Direct           4
   Background       1
   Direct           4

【问题讨论】:

    标签: python python-3.x pandas dataframe numpy


    【解决方案1】:

    试试这个:

    import pandas as pd
    
    text = ['Background', 'Clinical', 'Method', 'Direct', 'Background', 'Direct']
    df = pd.DataFrame(text, columns=['Text'])
    
    
    def create_idx_map():
        idx = 1
        values = {}
        for item in list(df['Text']):
            if item not in values:
                values[item] = idx
                idx += 1
        return values
    
    values = create_idx_map()
    df['Group'] = [values[x] for x in list(df['Text'])]
    
    print(df)
    

    【讨论】:

    • 函数create_idx_map()顺便可以简写成dict(map(reversed, enumerate(set(text))))(基本->当groups可以从0开始,否则需要加1)
    【解决方案2】:

    想法:列出Text 列的唯一值列表,对于Group 列,您可以在此唯一列表中分配值的索引。代码示例:

    df = pd.DataFrame({"Text": ["Background", "Clinical", "Clinical", "Method", "Background"]})
    
    # List of unique values of column `Text`
    groups = list(df["Text"].unique())
    
    # Assign each value in `Text` its index
    # (you can write `groups.index(text) + 1` when the first value shall be 1)
    df["Group"] = df["Text"].map(lambda text: groups.index(text))
    
    # Ouptut for df
    print(df)
    
    ### Result:
             Text  Group
    0  Background      0
    1    Clinical      1
    2    Clinical      1
    3      Method      2
    4  Background      0
    

    【讨论】:

      【解决方案3】:

      解决方案可能如下:

      import pandas as pd
      data = pd.DataFrame([["A B", 1], ["A C", 2], ["B A", 3], ["B C", 5]], columns=("name", "value"))
      data.groupby(by=[x.split(" ")[0] for x in data.loc[:,"name"]])
      

      您可以使用x.split(" ")[:NUMBER_OF_WORDS] 选择前几个单词。然后你将你想要的聚合应用到需要的对象上

      【讨论】:

        猜你喜欢
        • 2021-10-30
        • 1970-01-01
        • 2022-11-18
        • 2021-11-14
        • 2018-09-30
        • 2016-07-07
        • 1970-01-01
        • 1970-01-01
        • 2021-11-18
        相关资源
        最近更新 更多