![](/img/trans.png)
[英]making a list from values returned by a function inside a for-loop in python
[英]Extracting 2 values from list with for-loop
我有一個很大的 Excel 工作表,其中有一列包含幾個不同的標識符(例如 ISBN)。 我已將工作表轉換為熊貓數據框,並將帶有標識符的列轉換為列表。 原始列的一行的列表條目如下所示:
'ISBN:978-9941-30-551-1 Broschur : GEL 14.90, IDN:1215507534'
但是,它們並不完全相同,有些帶有 ISBN,有些沒有,有些條目較多,有些條目較少(在上面的示例中為 5),並且不同的 ID 大部分(但不是全部)由逗號。
在下一步中,我構建了一個函數,該函數遍歷各種列表項(一個長字符串,如上面的那個),然后將其拆分為不同的單詞(所以我得到類似
'ISBN:978-9941-30-551-1', 'Broschur :', 'GEL', '14.90', 'IDN:1215507534'
我希望提取 ISBN 和 IDN(如果存在)的值,然后將 ISBN 的指定列和 IDN 的指定列添加到我的原始數據幀(而不是包含混合數據的“標識符”列)。
我現在有以下代碼,哪種代碼可以完成它應該做的事情,但最終我的字典中只有列表,因此結果數據框中的每個條目都有一個列表。 我相信一定有更好的方法來做到這一點,但似乎無法想到......
def find_stuff(item):
list_of_words = item.split()
ISBN = list()
IDN = list()
for word in list_of_words:
if 'ISBN' in word:
var = word
var = var.replace("ISBN:", "")
ISBN.append(var)
if 'IDN' in word:
var2 = word
var2 = var2.replace("IDN:", "")
IDN.append(var2)
sum_dict = {"ISBN":ISBN, "IDN":IDN}
return sum_dict
output = [find_stuff(item) for item in id_lists]
print(output)
非常感謝任何幫助:)
由於您在pandas
工作,我建議使用熊貓的字符串方法來提取相關信息並將它們直接分配給新列。 在下面的答案中,我展示了一些可能性:
import pandas as pd
df = pd.DataFrame(['ISBN:978-9941-30-551-1 Broschur : GEL 14.90, IDN:1215507534'], columns=['identifier'])
def retrieve_text(lst, text):
try:
return [i for i in lst if text in i][0]
except:
return None
df['ISBN'] = df['identifier'].str.split().apply(lambda x: retrieve_text(x, 'ISBN')) #use a custom function to filter the list
df['IDN'] = df['identifier'].str.split().apply(lambda x: retrieve_text(x, 'IDN'))
df['name'] = df['identifier'].str.split().str[1] #get by index
df['price'] = df['identifier'].str.extract(r'(\d+\.\d+)').astype('float') #use regex, no need to split the string here
輸出:
標識符 | 國際標准書號 | 國際化域名 | 名稱 | 價錢 | |
---|---|---|---|---|---|
0 | ISBN:978-9941-30-551-1 Broschur: GEL 14.90, IDN:1215507534 | ISBN:978-9941-30-551-1 | IDN:1215507534 | 小冊子 | 14.9 |
您不需要函數,只需將帶有命名組的正則表達式應用於包含長字符串的原始列。
讓我們想象一下這個例子:
df = pd.DataFrame({'other_column': ['blah', 'blah'],
'identifier': ['ISBN:978-9941-30-551-1 Broschur : GEL 14.90, IDN:1215507534',
'ISBN:123-4567-89-012-3 blah IDN:1234567890 other'
],
})
other_column identifier
0 blah ISBN:978-9941-30-551-1 Broschur : GEL 14.90, IDN:1215507534
1 blah ISBN:123-4567-89-012-3 blah IDN:1234567890 other
如果ISBN
總是在IDN
之前,您可以使用pandas.Series.str.extract
:
df['identifier'].str.extract('(?P<ISBN>ISBN:[\d-]+).*(?P<IDN>IDN:\d+)')
輸出:
ISBN IDN
0 ISBN:978-9941-30-551-1 IDN:1215507534
1 ISBN:123-4567-89-012-3 IDN:1234567890
如果有可能不總是按此順序存在,則使用pandas.Series.str.extractall
並使用groupby
重新處理輸出:
(df['identifier'].str.extractall('(?P<ISBN>ISBN:[\d-]+)|(?P<IDN>IDN:\d+)')
.groupby(level=0).first()
)
最后,如果您不想要標識符名稱,請將正則表達式更改為'(?:ISBN:(?P<ISBN>[\\d-]+))|(?:IDN:(?P<IDN>\\d+))'
:
(df['identifier'].str.extractall('(?:ISBN:(?P<ISBN>[\d-]+))|(?:IDN:(?P<IDN>\d+))')
.groupby(level=0).first()
)
輸出:
ISBN IDN
0 978-9941-30-551-1 1215507534
1 123-4567-89-012-3 1234567890
注意。 如果您需要字典作為輸出,您可以在命令末尾附加.to_dict('index')
。 這給你
{0: {'ISBN': '978-9941-30-551-1', 'IDN': '1215507534'},
1: {'ISBN': '123-4567-89-012-3', 'IDN': '1234567890'}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.