假设我有一个数据框:
name lat lon
0 Changchong-Luya Creek (Sta. 0+000-1+680) Start 15.085700 120.919967
1 Sudan Creek (Sta. 0+000 - 3+200) Start 15.073000 120.915930
2 Sudan Creek (Sta. 0+000 - 3+200) End 15.079350 120.893350
3 Nikko Boss Creek (Sta. 0+000 - 3+000) Start 15.079980 120.912930
4 Nikko Boss Creek (Sta. 0+000 - 3+000) End 15.076720 120.925670
如果要满足条件,我想合并两行:
结果数据框为:
name start_lat start_lon end_lat end_lon
0 Sudan Creek 15.073000 120.915930 15.079350 120.893350
1 Nikko Boss Creek 15.079980 120.912930 15.076720 120.925670
我已经遍历了行,但是正则表达式的混合是否有一些熊猫方式?
答案 0 :(得分:2)
这是我的方法:
# extract the information and join
new_df = df.join(df['name'].str.extract('(.*) \(.*\) (Start|End)'))
# pivot
new_df = new_df.pivot(index=0, columns=1, values=['lat','lon'])
# flatten column names
new_df.columns = [f'{b.lower()}_{a}' for a,b in new_df.columns]
# remove nan
new_df.dropna(how='any')
输出:
end_lat start_lat end_lon start_lon
0
Nikko Boss Creek 15.07672 15.07998 120.92567 120.91293
Sudan Creek 15.07935 15.07300 120.89335 120.91593