Как перебрать строки ячейки данных? - PullRequest
0 голосов
/ 18 апреля 2020

У меня есть датафрейм с текстом в каждой ячейке. Я хочу перебрать кадр данных и отдельные символы его ячеек и заполнить список либо 0 для наличия пробела, либо 1 для наличия символа. Я попробовал itertuples, iterrows и iteritems, но для всех я не могу получить доступ к каждому отдельному символу строки.

crispr = pd.DataFrame({'Name': ['Bob', 'Jane', 'Alice'], 
                       'Issue': ['Handling data', 'Could not read sample', 'No clue'],
                       'Comment': ['Need to revise data', 'sample preparation', 'could not find out where problem occurs']})

Я попробовал:

dflist = []
countchar= 0
for i,j in crispr.iteritems():
    for x in range(len(j)):
        test = j[countchar].isspace()
        countchar+=1
        if test == True:
            dflist.append(0)
        else:
            dflist.append(1)

Я пытался вычислить out, если он будет работать с itertuples или iterrows ():

for i in crispr.itertuples():
    for j in i:
        for b in j:
            print(b)

Возникает следующая ошибка:

 TypeError: 'int' object is not iterable  

Ожидаемый вывод - список, содержащий 1 для символа и 0 для пробела :

dflist = [[1,1,1], [1,1,1,1], [1,1,1,1,1]],[[1,1,1,1,1,1,1,0,1,1,1,1], ...]]

1 Ответ

1 голос
/ 18 апреля 2020

Ваш опубликованный код (до вашего последнего редактирования) был неисправен, в нем было много неизвестного, что выдает ошибки, отличные от того, что вы опубликовали. Я исправил ваш код так:

dflist = []                    # added this
for i,j in crispr.iteritems():
    for x in range(len(j)):
        test = j[x].isspace()  # changed countchar to x
        # countchar+=1         # removed this
        if test == True:
            dflist.append(0)
        else:
            dflist.append(1)

for i in crispr.itertuples():
    for j in i:
        for b in j:  # this procudes your error
            print(b)

Если вы осмотрите первый элемент j, вы увидите его значение 0 - отсюда и ошибка. Вы не можете перебрать 0.

Решение:

import pandas as pd

crispr = pd.DataFrame({
    'Name': ['Bob', 'Jane', 'Alice'],
    'Issue': ['Handling data', 'Could not read sample', 'No clue'],
    'Comment': ['Need to revise data', 'sample preparation', 
                'could not find out where problem occurs']})

print(crispr)
outer_list = []
for i,j in crispr.iteritems():
    dflist = []
    for word in j:
        wordlist = [] 
        for char in word:
            if char.isspace():
                wordlist.append(0)
            else:
                wordlist.append(1)
        dflist.append(wordlist)
    outer_list.append(dflist)

print(outer_list)

Вывод (добавлены комментарии для ясности):

                                   Comment                  Issue   Name
0                      Need to revise data          Handling data    Bob
1                       sample preparation  Could not read sample   Jane
2  could not find out where problem occurs                No clue  Alice

# Comment
[[[1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1], 
  [1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 
  [1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 
   1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1]], 
 # Issue
 [[1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1], 
  [1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1], 
  [1, 1, 0, 1, 1, 1, 1]],
 # Name 
 [[1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1, 1]]]

должен делать то, что вы хотите.

...