[英]Pandas Iterate list within a dataframe cell
我正在研究一個數據框,該數據框有一個“書籍”列,每個單元格中有一個書籍列表。 這是“書籍”列中的示例單元格內容:
["{"book_name":"abc","book_size":"43","requestor":"97457239247","comments":"this is a comment"}",
"{"book_name":"def","book_size":"453","requestor":"27657899462","comments":"this is a comment"}"]
我試圖遍歷單元格以查找具有特定請求者的書,然后獲取整個書對象並將其粘貼到新列中。
我的代碼:
def find_hipri_book(books):
for book in books:
if '27657899462' in book:
return book
df['hipri_book'] = df['books'].apply(find_hipri_book)
我也試過:
def find_hipri_book(row):
for book in row['books']:
if '27657899462' in book:
return book
df['hipri_book'] = df.apply(find_hipri_book, axis=1)
以上都給出了'float' object is not iterable
錯誤。 請告訴我我做錯了什么?
你可以這樣做:
a = [{"book_name":"abc","book_size":"43","requestor":"97457239247","comments":"this is a comment"},
{"book_name":"def","book_size":"453","requestor":"27657899462","comments":"this is a comment"}]
pd.DataFrame(a).loc[lambda x:x.requestor == '27657899462'].to_dict('records')
[{'book_name': 'def',
'book_size': '453',
'requestor': '27657899462',
'comments': 'this is a comment'}]
甚至:
pd.DataFrame(a).query("requestor == '27657899462'").to_dict('records')
[{'book_name': 'def',
'book_size': '453',
'requestor': '27657899462',
'comments': 'this is a comment'}]
如果這些是字符串而不是字典,yu 必須將它們轉換為字典,然后其余的隨之而來。 例如
b = ['{"book_name":"abc","book_size":"43","requestor":"97457239247","comments":"this is a comment"}',
'{"book_name":"def","book_size":"453","requestor":"27657899462","comments":"this is a comment"}']
pd.DataFrame(pd.Series(b).apply(eval).tolist()).query("requestor == '27657899462'").to_dict('records')
[{'book_name': 'def',
'book_size': '453',
'requestor': '27657899462',
'comments': 'this is a comment'}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.