【问题标题】:Conditional String Split based on another column str Python基于另一列 str Python 的条件字符串拆分
【发布时间】:2019-03-09 10:47:24
【问题描述】:

大家好,有没有一种干净的方法可以将这些数据组织到正确的列中以便以后对其进行地理定位?

 import pandas as pd

 coordinates = {'event': ['1', '2', '3', '4'],
     'direction': ['E', 'E,N', 'N,E', 'N'],
     'location': ['316904', '314798,5812040', '5811316,314766', '5811309']}
 df = pd.DataFrame.from_dict(coordinates)
 df

它需要它的样子:

 Event  direction    location    easting    northing
  1       E          316904       316904       NA
  2       E,N     314798,5812040   314798    5812040
  3       N,E     5811316,314766   314766    5811316
  4       N          5811309         NA      5811309

我可以使用以下方式拆分位置: df['easting'], df['northing'] = df['location'].str.split(',',1).str

但是当 E THEN 第一个值是东移,第二个北移时,我需要 条件N 大于第一个值时的条件为东向 等等..

任何想法都将不胜感激!

【问题讨论】:

    标签: python regex string pandas


    【解决方案1】:

    解决方案 1:

    首先将split 列替换为新列,然后通过startswith 创建的布尔掩码交换值:

    df[['easting','northing']] = df['location'].str.split(',',1, expand=True)
    mask = df['direction'].str.startswith('N')
    df.loc[mask, ['easting','northing']] = df.loc[mask, ['northing','easting']].values
    
    print (df)
      event direction        location easting northing
    0     1         E          316904  316904     None
    1     2       E,N  314798,5812040  314798  5812040
    2     3       N,E  5811316,314766  314766  5811316
    3     4         N         5811309    None  5811309
    

    解决方案 2:

    首先将值展平到助手DataFrame,然后使用pivot,最后由join 加入原始值:

    from itertools import chain
    
    direc = df['direction'].str.split(',')
    loc = df['location'].str.split(',')
    lens = loc.str.len()
    df1 = pd.DataFrame({
        'direction' : list(chain.from_iterable(direc.tolist())), 
        'loc' : list(chain.from_iterable(loc.tolist())), 
        'event' : df['event'].repeat(lens)
    })
    
    df2 = df1.pivot('event','direction','loc').rename(columns={'E':'easting','N':'northing'})
    print (df2)
    direction easting northing
    event                     
    1          316904      NaN
    2          314798  5812040
    3          314766  5811316
    4             NaN  5811309
    
    df = df.join(df2, on='event')
    print (df)
      event direction        location easting northing
    0     1         E          316904  316904      NaN
    1     2       E,N  314798,5812040  314798  5812040
    2     3       N,E  5811316,314766  314766  5811316
    3     4         N         5811309     NaN  5811309
    

    【讨论】:

    • 第一个解决方案创造了奇迹! Jezrael 我欠一个好咖啡哥 tks!
    猜你喜欢
    • 2015-06-08
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多