Заменить столбец данных с разделенными столбцами - PullRequest
0 голосов
/ 30 марта 2020

Как я могу заменить столбец dataframe столбцами после его разделения? Я знаю, как разделить столбец, но не знаю, как заменить его столбцами с разделенным значением.

Ввод:

import pandas as pd

df = pd.DataFrame({'id': [101, 102],
                   'full_name': ['John Brown', 'Bob Smith'],
                   'birth_year': [1960, 1970]})
df_new = df['full_name'].str.split(" ", expand=True)
print(df)
print(df_new)

Вывод:

    id   full_name  birth_year
0  101  John Brown        1960
1  102   Bob Smith        1970
      0      1
0  John  Brown
1   Bob  Smith

Ожидаемый результат:

    id first_name last_name  birth_year
0  101       John     Brown        1960
1  102        Bob     Smith        1970

Ответы [ 3 ]

1 голос
/ 30 марта 2020
df.join(df.full_name.str.split('\s', expand = True) \
                                    .set_axis(['first_name', 'last_name'], axis = 1)) \
                                                [['id', 'first_name', 'last_name', 'birth_year']]

Выход:

    id   full_name  birth_year
0  101  John Brown        1960
1  102   Bob Smith        1970
1 голос
/ 31 марта 2020

Стратегия состоит в том, чтобы получить позицию столбца, которую вы будете заменять sh, создать новые столбцы и объединить новые и старые кадры данных относительно позиции столбца u wi sh для замены:

#get the position of the column to be replaced
col_position = df.columns.get_loc('full_name')

#create new dataframe that holds the new columns
insert_df = (df
            .pop('full_name')
            .str.split(expand=True)
            .set_axis(['first_name','last_name'],axis='columns')
            )

df_by_positions = (#this is the dataframe before col_position
                   [df.iloc[:,:col_position],
                   #this is the dataframe we are inserting
                   insert_df,
                  #this is the dataframe after col_position
                  df.iloc[:,col_position:]
                  ]
                  )

pd.concat(df_by_positions,axis=1)

     id first_name  last_name   birth_year
0   101   John       Brown       1960
1   102   Bob        Smith       1970
0 голосов
/ 30 марта 2020

Давайте использовать str.extract с регулярными выражениями и именованными группами:

df.join(df['full_name'].str.extract(r'(?P<first_name>\w+)\s(?P<last_name>\w+)'))\
  .drop('full_name', axis=1)

Вывод:

    id  birth_year first_name last_name
0  101        1960       John     Brown
1  102        1970        Bob     Smith
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...