簡體   English   中英

我無法從 pandas dataframe 字典中提取字符串

[英]I am unable to extract a string from within a pandas dataframe dictionary

我的 dataframe 看起來像這樣:

這是一個示例條目:

 [ { "type": "bold", "text": "Raeesah Khan testifies to privileges committee that WP leaders told her to keep to lie made in Parliament\n\n" }, "Ms Raeesah said that when she met the three WP leaders on Aug 8, they told her that the best thing for her to do would be to continue with the narrative that she had already given in Parliament on Aug 3. They also told her that if she and the WP could get away with it, there was no need to clarify the lie. \n\n➡️ ", { "type": "link", "text": "https://tdy.sg/3rx9Rli" }, "\n\n", { "type": "mention", "text": "@todayonlinesg" }, "" ]

我正在嘗試提取附加到“文本:”字典條目的字符串,但我無法這樣做。

鍵入:

df_new['text'] = df_new.apply(lambda x: x.text[0]['text'], axis=1)

產量:

IndexError: string index out of range

IIUC,似乎每一行都是一個包含多個項目的列表,並且您想要訪問第一項(這是一個字典)並從該字典中獲取'text'鍵的值。 所以這應該工作:

df_new['text'] = df_new['text'].str[0].str.get('text')

再說一次,您的錯誤表明某些行是空字符串。 在這種情況下,請嘗試:

df_new['text'] = df_new['text'].apply(lambda x: '' if x == '' else x[0]['text'])

無論如何,您需要在問題中包含更多數據以使其更清晰。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM