[英]create new columns on pandas based on one column elements
我有一個 dataframe 列如下:
column_1
0 0.25 / 0 / 0.25 / -0.25
1 -0.25 / 0 /1
2 0 / -0.5 / -0.25
3 1/ 0.25 / -0.75
每行由連續數字鏈組成(由 / 分隔)我想創建 2 個新列,並且只保留第一個元素和最后一個元素,如下例所示
column_1 new_column_1st_element new_column_last_element
0 0.25 / 0 / 0.25 / -0.25 0.25 -0.25
1 -0.25 / 0 /1 -0.25 1
2 0 / -0.5 / -0.25 0 -0.25
3 1/ 0.25 / -0.75 1 -0.75
假設column_1
具有字符串數據類型的數據
df['new_column_1st_element'] = df.apply(lambda row: row['column_1'].split('/')[0], axis = 1)
類似地,這可以為new_column_last_element
完成
使用Series.str.extract
以及給定的正則表達式模式:
df[['first', 'last']] = df['column_1'].str.extract(r'([^/]+).*?([^/]+)$')
結果:
# print(df)
column_1 first last
0 0.25 / 0 / 0.25 / -0.25 0.25 -0.25
1 -0.25 / 0 /1 -0.25 1
2 0 / -0.5 / -0.25 0 -0.25
3 1/ 0.25 / -0.75 1 -0.75
您可以在here
測試regex
模式。
這里是 go:
df['new_column_1st_element'] = df.column_1.str.split('/').str[0]
df['new_column_last_element'] = df.column_1.str.split('/').str[-1]
Output
column_1 new_column_1st_element new_column_last_element
0 0.25 / 0 / 0.25 / -0.25 0.25 -0.25
1 -0.25 / 0 /1 -0.25 1
2 0 / -0.5 / -0.25 0 -0.25
3 1/ 0.25 / -0.75 1 -0.75
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.