Соединение слов в столбцах - PullRequest
0 голосов
/ 10 июня 2019

Фон

У меня есть следующий код

import pandas as pd
#create df
df = pd.DataFrame({'Before' : ['there are many different', 
                               'i like a lot of sports ', 
                               'the middle east has many '], 
                   'After' : ['in the bright blue box', 
                               'because they go really fast ', 
                               'to ride and have fun '],

                  'P_ID': [1,2,3], 
                  'Word' : ['crayons', 'cars', 'camels'],
                  'N_ID' : ['A1', 'A2', 'A3']

                 })

#rearrange
df = df[['P_ID', 'N_ID', 'Before', 'Word','After']]

, который создает следующие значения: df

  P_ID  N_ID    Before                 Words       After
0   1   A1   there are many different   crayons     in the bright blue box
1   2   A2  i like a lot of sports      cars      because they go really fast
2   3   A3  the middle east has many    camels      to ride and have fun

Цели

1) Соедините слова в столбцах Before и After со словами в столбце Word

2) Создайте new_column

Требуемый вывод

A new_column со следующим выводом

new_column
there are many different crayons in the bright blue box
i like a lot of sports cars because they go really fast
the middle east has many camels to ride and have fun

Вопрос

Как мне выполнить мойцель

Ответы [ 3 ]

2 голосов
/ 10 июня 2019

Вы можете просто добавить эти столбцы:

df['new_column'] = df['Before'] + ' ' + df['Word'] + ' ' + df['After']

Вот полный код:

import pandas as pd
#create df
df = pd.DataFrame({'Before' : ['there are many different', 
                               'i like a lot of sports ', 
                               'the middle east has many '], 
                   'After' : ['in the bright blue box', 
                               'because they go really fast ', 
                               'to ride and have fun '],

                  'P_ID': [1,2,3], 
                  'Word' : ['crayons', 'cars', 'camels'],
                  'N_ID' : ['A1', 'A2', 'A3']

                 })

#rearrange
df = df[['P_ID', 'N_ID', 'Word', 'Before', 'After']]
df['new_column'] = df['Before'] + ' ' + df['Word'] + ' ' + df['After']
df['new_column']
0    there are many different crayons in the bright...
1    i like a lot of sports  cars because they go r...
2    the middle east has many  camels to ride and h...
Name: new_column, dtype: object
1 голос
/ 10 июня 2019

Вы можете использовать метод cat () метода доступа .str

df['New_column'] = df['Before'].str.cat(df[['Word','After']],sep=" ")
  • cat () даже позволяет добавить разделитель
  • Объединение нескольких столбцов - это просто передача списка последовательностей или информационного кадра, содержащего все столбцы, кроме первого, в качестве параметра для str.cat (), вызываемого в первом столбце (До):

код:

import pandas as pd
#create df
df = pd.DataFrame({'Before' : ['there are many different',
                               'i like a lot of sports ',
                               'the middle east has many '],
                   'After' : ['in the bright blue box',
                               'because they go really fast ',
                               'to ride and have fun '],

                  'P_ID': [1,2,3],
                  'Word' : ['crayons', 'cars', 'camels'],
                  'N_ID' : ['A1', 'A2', 'A3']

                 })

#rearrange
df = df[['P_ID', 'N_ID', 'Before', 'Word','After']]
print (df)
df['New_column'] = df['Before'].str.cat(df[['Word','After']],sep=" ")
print (df)
1 голос
/ 10 июня 2019

Вы можете добавить столбцы, как предложено выше, или более общее решение многих подобных проблем, которые могут возникнуть:

df['new_column']=df.apply(lambda x: x.Before+x.Word+x.After, axis=1)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...