[英]Pandas DataFrame: Replace based on filter and regex extract
這是我的數據框的一部分:
Type Date Diff Data
0 Section 20171204 1.0 ~
1 Korean 20171204 1.0 저는 유양이에요.
2 English 20171204 1.0 Im Yooyang.
3 Theme 20171204 1.0 {"zh":"介紹","vi":"giới thiệu","ko":"소개","en":"I...
有超過 10,000 行,其中約 500 行是“主題”類型。
我試圖只用韓文替換主題數據,即{"zh":"介紹","vi":"giới thiệu","ko":"소개","en":"I...
變成소개
。
我可以使用正則表達式([가-힣]+)
。
我嘗試使用df[df['Type'] == 'Theme'][['Data']].T.squeeze().str.extract('([가-힣]+)')
,但我不知道如何將其合並回原始 df ( df[df['Type'] == 'Theme'][['Data']] =
不工作。
我嘗試替換,但我似乎不能只為主題數據做到這一點。
顯然我不應該使用迭代器: https : //pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iterrows.html
您可以將map
方法與匿名幫助函數一起使用,將字符串轉換為帶有json.loads
的 dict 並通過loc
索引:
import json
df.loc[df.Type == 'Theme', 'Data'] = df.loc[df.Type == 'Theme', 'Data'].map(lambda x: json.loads(x)["ko"])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.