![](/img/trans.png)
[英]Pandas dataframe: Creating a new column based on data from other columns
[英]Extract data from a pandas dataframe strings column and generate new columns based on content in it
我有一個 pandas 列,其中包含如下數據:
**標題**:New_ind
**正文**:檢測錯誤
*respo_URL **: www.github.com
**respo_status **:{顏色}
data = {'sl no': [661, 662],
'key': ['3484', '3483'],
'id': [13592349, 13592490],
'Sum': ['[E-1]', '[E-1]'],
'Desc': [
"**Title **: New_ind\n\n**Body **: Detection_error\n\n*respo_URL **: www.github.com\n\n**respo_status **: {yellow}","**Title **: New_ind2\n\n**Body **: import_error\n\n*respo_URL **: \n\n**respo_status **: {green}"]}
df = pd.DataFrame(data)
我需要生成新列,其中 Title、Body、response_URL 等將是列名,后面的所有內容:應該是這些列單元格中包含的值。 只是提一下列中的項目不是字典
使用正則表達式有多種方法可以做到這一點,但我發現使用str
方法最清楚:
desc_df = df["Desc"].str.split("\n\n", expand=True)
for col in desc_df.columns:
desc_df[col] = desc_df[col].str.split(":").str[1].str.strip()
colnames = "Title", "Body", "respo_URL", "respo_status"
desc_df = desc_df.rename(columns=dict(enumerate(colnames)))
df = pd.concat([df.drop(columns="Desc"), desc_df], axis=1)
\n\n
拆分列Desc
並將結果展開為 dataframe desc_df
。:
拆分每個新列,取右側,並去除空格。Desc
列和desc_df
。示例結果:
sl no key id Sum Title Body respo_URL \
0 661 3484 13592349 [E-1] New_ind Detection_error www.github.com
1 662 3483 13592490 [E-1] New_ind2 import_error
respo_status
0 {yellow}
1 {green}
以下正則表達式版本適用於該示例,但我認為它不如另一個強大:
pattern = "\n\n".join(
f"\*+{col} \*+: (?P<{col}>[^\n]*)"
for col in ("Title", "Body", "respo_URL", "respo_status")
)
desc_df = df["Desc"].str.extract(pattern)
df = pd.concat([df.drop(columns="Desc"), desc_df], axis=1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.