【问题标题】:Python - Extracting specific data from rows based on a condition in a dataframePython - 根据数据框中的条件从行中提取特定数据
【发布时间】:2021-11-27 19:38:42
【问题描述】:

我正在尝试做的事情:我有以下数据框。我需要捕获空间超过 4 的数据行并将信息放入单独的字典中。 例如 - 2. harry potterA. test book 之间的行将被捕获,A. test bookF. book3 之间的行也将被捕获(所需的输出如下所示) 我无法预先定义字典的数量,因为我不知道需要多少,因为它取决于数据。

数据框示例:


name           | A | space
---------------|---|------
2. harry potter| 1 | 2    
   jk rowling  | 1 | 4   
   testing     | 3 | 4
A. test book   | 4 | 2
   author1     | 4 | 4
   author2     | 4 | 4
   author3     | 4 | 4
F. book3       | 5 | 2

期望的输出:

dict_A = {name:'jk rowling',testing', A: '1','3', space: '4','4'}
dict_B = {name:'author1', 'author2', 'author3', A:'4','4','4', space: '4','4','4'}

我尝试过的:

lst_A =[]

for i in df["name"]:
    if not i.startswith(('2.','A.','F.')):
        if len(i) - len(i.lstrip()) > 3:
            lst_A.append(i)
        else:
            if i.startswith(('2.','A.','F.')):
                pass
            

df 作为字典:

上面的代码只为我提供了超过 4 个空格的列名中的数据 - 但是我无法将它正确地分离到单独的列表/字典中并捕获所有信息。有人能帮我指出正确的方向吗?

对于参考:df 作为字典:

{'name': {0: '2. harry potter',
  1: '   jk rowling  ',
  2: '   testing     ',
  3: 'A. test book   ',
  4: '   author1     ',
  5: '   author2     ',
  6: '   author3     ',
  7: 'F. book3       '},
 'A': {0: 1, 1: 1, 2: 3, 3: 4, 4: 4, 5: 4, 6: 4, 7: 5},
 'space': {0: 2, 1: 4, 2: 4, 3: 2, 4: 4, 5: 4, 6: 4, 7: 2}}

【问题讨论】:

  • 你能提供你的数据框作为字典吗? (df.to_dict())
  • @mozway 也将添加到问题中:{'name': {0: '2. harry potter', 1: ' jk rowling ', 2: ' testing ', 3: 'A. test book ', 4: ' author1 ', 5: ' author2 ', 6: ' author3 ', 7: 'F. book3 '}, 'A': {0: 1, 1: 1, 2: 3, 3: 4, 4: 4, 5: 4, 6: 4, 7: 5}, 'space': {0: 2, 1: 4, 2: 4, 3: 2, 4: 4, 5: 4, 6: 4, 7: 2}}
  • 谢谢,我提供了a solution

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


【解决方案1】:

为此,我会使用掩码选择您想要的数据,然后循环选择(使用DataFrame.iterrows()DataFrame.itertuples()

首先创建掩码

mask = df['A'] > df['space']
selected_rows = df.loc[mask, :]
# Loop through these rows

【讨论】:

    【解决方案2】:

    您可以使用以下内容:

    # remove spaces from 'name' (if needed to keep original df, make a copy first)
    df['name'] = df['name'].str.strip()
    
    # create group
    m = df['space'].eq(4)
    group = (m & (~m.shift(fill_value=False))).cumsum().where(m)
    
    # create dictionary of dict
    out = {'dict_%d' % k: d.to_dict('list') for k,d in df.groupby(group)}
    

    输出:

    {'dict_1': {'name': ['jk rowling', 'testing'], 'A': [1, 3], 'space': [4, 4]},
     'dict_2': {'name': ['author1', 'author2', 'author3'], 'A': [4, 4, 4], 'space': [4, 4, 4]},
    }
    

    访问字典:

    >>> out['dict_1']
    {'name': ['jk rowling', 'testing'], 'A': [1, 3], 'space': [4, 4]}
    

    【讨论】:

      猜你喜欢
      • 2023-03-07
      • 2020-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      • 2018-09-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多