Мне удалось вытащить список из источника данных. Элементы списка отформатированы следующим образом (обратите внимание, что первое число НЕ является индексом):
0 cheese 100
1 cheddar cheese 1100
2 gorgonzola 1300
3 smoked cheese 200
и т.п.
Это означает, что при печати одна строка содержит «0 cheese 100» со всеми пробелами.
Что я хотел бы сделать, так это проанализировать каждую запись, чтобы разделить ее на два списка. Мне не нужен первый номер. Вместо этого я хочу тип сыра и номер после.
Например:
cheese
cheddar cheese
gorgonzola
smoked cheese
и:
100
1100
1300
200
Конечная цель состоит в том, чтобы иметь возможность атрибутировать два списка столбцам в pd.DataFrame, чтобы их можно было обрабатывать по-своему.
Любая помощь очень ценится.






Я думаю, что что-то в этих строках может сработать:
import pandas as pd
import re
mylist=['0 cheese 100','1 cheddar cheese 200']
numbers = '[0-9]'
list1=[i.split()[-1] for i in mylist]
list2=[re.sub(numbers, '', i).strip() for i in mylist]
your_df=pd.DataFrame({'name1':list1,'name2':list2})
your_df
Да, извините, я пропустил их. Я отредактировал свой предыдущий ответ сейчас. Если структура всегда такая, использование регулярных выражений может помочь вам исключить числа из общей строки.
Если целью является фрейм данных, почему бы просто не сделать это, а не два списка. Если вы превратите свою строку в серию, вы можете использовать pandas.Series.str.extract(), чтобы разделить ее на нужные столбцы:
import pandas as pd
s = '''0 cheese 100
1 cheddar cheese 1100
2 gorgonzola 1300
3 smoked cheese 200'''
pd.Series(s.split('\n')).str.extract(r'.*?\s+(?P<type>.*?)\s+(?P<value>\d+)')
Это дает Dataframe:
type value
0 cheese 100
1 cheddar cheese 1100
2 gorgonzola 1300
3 smoked cheese 200
Кроме того, для решения pd.Series.str лично я бы использовал .str.split('\s\s+', expand=True) и удалил первый столбец~
IIUC ваши строки являются элементами списка. Вы можете использовать re.split, чтобы разделить два или более пробела:
import re
import pandas as pd
your_list = [
"0 cheese 100",
"1 cheddar cheese 1100",
"2 gorgonzola 1300",
"3 smoked cheese 200",
]
df = pd.DataFrame([re.split(r'\s{2,}', s)[1:] for s in your_list], columns=["type", "value"])
Вывод:
type value
0 cheese 100
1 cheddar cheese 1100
2 gorgonzola 1300
3 smoked cheese 200
Могу ли я предложить это простое решение:
lines = [
"1 cheddar cheese 1100 ",
"2 gorgonzola 1300 ",
"3 smoked cheese 200",
]
for line in lines:
words = line.strip().split()
print( ' '.join( words[1:-1]), words[-1])
Результат:
cheddar cheese 1100
gorgonzola 1300
smoked cheese 200
Вы можете добиться этого, используя нарезку:
from curses.ascii import isdigit
inList = ['0 cheese 100', '1 cheddar cheese 1100', '2 gorgonzola 1300', '3 smoked cheese 200']
cheese = []
prices = []
for i in inList:
temp = i[:19:-1] #Cuts out first number and all empty spaces until first character and reverses the string
counter = 0
counter2 = 0
for char in temp: #Temp is reversed, meaning the number e.g. '100' for 'cheese' is in front but reversed
if char.isdigit():
counter += 1
else: #If the character is an empty space, we know the number is over
prices.append((temp[:counter])[::-1]) #We know where the number begins (at position 0) and ends (at position counter), we flip it and store it in prices
cheeseWithSpace = (temp[counter:]) #Since we cut out the number, the rest has to be the cheese name with some more spaces in front
for char in cheeseWithSpace:
if char == ' ': #We count how many spaces are in front
counter2 += 1
else: #If we reach something other than an empty space, we know the cheese name begins.
cheese.append(cheeseWithSpace[counter2:][::-1]) #We know where the cheese name begins (at position counter2) cut everything else out, flip it and store it
break
break
print(prices)
print(cheese)
Просмотрите комментарии в коде, чтобы понять подход. В основном вы переворачиваете свои строки, используя [::-1], чтобы упростить их обработку. Затем вы удаляете каждую часть по одной.
Если у вас есть:
text = '''0 cheese 100
1 cheddar cheese 1100
2 gorgonzola 1300
3 smoked cheese 200'''
# OR
your_list = [
'0 cheese 100',
'1 cheddar cheese 1100',
'2 gorgonzola 1300',
'3 smoked cheese 200'
]
text = '\n'.join(your_list)
Делает:
from io import StringIO
df = pd.read_csv(StringIO(text), sep='\s\s+', names=['col1', 'col2'], engine='python')
print(df)
Вывод:
col1 col2
0 cheese 100
1 cheddar cheese 1100
2 gorgonzola 1300
3 smoked cheese 200
df=df.reset_index(drop=True), если хотите.
Вы удобно пропустили данные с пробелами, такими как
cheddar cheese. Что происходит с ними?