Skip to main content
 首页 » 编程设计

python pandas : dataframe grouped by a column(such as, name), 并获取每组中部分列的值

2024年10月17日8cyq1162

有一个名为 df 的数据框,如下所示:

  name   id    age             text  
   a      1     1    very good, and I like him 
   b      2     2    I play basketball with his brother 
   c      3     3    I hope to get a offer 
   d      4     4    everything goes well, I think 
   a      1     1    I will visit china 
   b      2     2    no one can understand me, I will solve it 
   c      3     3    I like followers 
   d      4     4    maybe I will be good 
   a      1     1    I should work hard to finish my research 
   b      2     2    water is the source of earth, I agree it 
   c      3     3    I hope you can keep in touch with me 
   d      4     4    My baby is very cute, I like him 

你知道,有四个名字:a、b、c、d。每个名字都有 ID、年龄和文本。其实每个名字组的id,age都是一样的,但是每个名字组的text是不同的,每个名字三行(这个只是例子,真实数据是一个大数据)

我想获取每个名称组的 ID、年龄(例如)。另外,我想通过函数extract_text(text) 计算文本中每个组在所有文本中的字符索引。我的意思是我想获取以下数据:以姓名'a'为例:age: 1, id: 1. 'I'索引三行(我只是举个例子,不是真实的):20, 0, 0.

我尝试过如下操作:

 import  pandas as pd 
 
 def extract_text(text): 
     index_n = None 
     text_len = len(text) 
     for i in range(0, text_len, 1): 
         if text[i] == 'I': 
            index_n = i 
     return index_n 
 
 
 
 df = pd.DataFrame({'name': ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd',      
                            'a', 'b', 'c', 'd'], 
               'id': [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4], 
               'age':[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4], 
               'text':['very good, and I like him',  
                       'I play basketball with his brother', 
                       'I hope to get a offer',  
                       'everything goes well, I think', 
                       'I will visit china',  
                       'no one can understand me, I will solve it', 
                       'I like followers', 'maybe I will be good', 
                       'I should work hard to finish my research',                  
                       'water is the source of earth, I agree it', 
                       'I hope you can keep in touch with me',  
                       'My baby is very cute, I like him']}) 
 
 
  id_num = df.groupby('name')['id'].value[0] 
  id_num = df.groupby('age')['id'].value[0] 
  index_num = df.groupby('age')['text'].apply(extract_text) 

但是有错误:

Traceback (most recent call last):File
bot_test_new.py", line 25, in
id_num = df.groupby('name')['id'].value[0]
AttributeError: 'SeriesGroupBy' object has no attribute 'value'

请给我你的手,提前致谢!

请您参考如下方法:

我会在评论中详细说明。问题是 extract_text 只能处理单个字符串。但是,当您分组然后应用时,您将发送一个包含组中所有字符串的列表。

有两种解决方案,第一种是我指出的(发送单独的字符串):

index_num = df.groupby('age')['text'].apply(lambda x: [extract_text(_) for _ in x])  

另一个正在更改 extract_text 以便它可以处理字符串列表:

 def extract_text(list_texts): 
    list_index = [] 
    for text in list_texts: 
        index_n = None 
        text_len = len(text) 
        for i in range(0, text_len, 1): 
            if text[i] == 'I': 
                index_n = i 
        list_index.append(index_n) 
    return list_index 

然后继续:

index_num = df.groupby('age')['text'].apply(extract_text) 

此外,您可以使用 text.find("I") 代替 extract_text 中的循环。像这样的东西 def extract_text(list_texts): return [text.find("I") for text in list_texts]。