Concat two columns values of dataframe
Since Age
is an int
column, you need to cast it to str
using astype
In [2511]: df['Name'] = df["Age"].astype(str) + " " + df["Name"]
In [2511]: df['Name']
Out[2511]:
0 10 Alex
1 12 Bob
2 13 Clarke
How to do column string concatenation including space separator in Pandas dataframe?
You can also add separator between columns:
df['alltext'] = df['txt1'] + ' ' + df['txt2'] + ' ' + df['txt3']
Or filter by DataFrame.filter
only columns with txt
in column name and use join
per rows with apply
:
df['alltext'] = df.filter(like='txt').apply(' '.join, axis=1)
Or filter only object columns by DataFrame.select_dtypes
- most times a Series
with a dtype of object is going to be a string
- but it could be any Python object
:
df['alltext'] = df.select_dtypes('object').apply(' '.join, axis=1)
Or select columns by positions - all columns without first by DataFrame.iloc
:
df['alltext'] = df.iloc[:, 1:].apply(' '.join, axis=1)
Thank you, @Jon Clements for solution for better matching columns names with txt
and numeric:
df['alltext'] = df.filter(regex=r'^txt\d+$').apply(' '.join, axis=1)
How to string-concatenate multiple string columns in pandas?
Use agg
with append
:
df = df.append(df.agg(' '.join), ignore_index=True)
df
string1 string2
0 Hello This is Sam
1 how are you? from Canada
2 Hello how are you? This is Sam from Canada
Concatenate string and Pandas field in an apply lambda
I guess you want to check if values in one column end with another. You can achieve that by calling apply on multiple columns.
Provided that df
is:
Field B Field A
0 1/a.pdf a
1 2/b.pdf b
2 3/b.pdf c
3 4/c.pdf d
You can apply some lambda along the axis 1
df[['Field A', 'Field B']].apply(lambda item: item['Field A'].endswith(item['Field B'] + '.pdf'), axis=1)
Output:
0 True
1 True
2 False
3 False
dtype: bool
Edit: To have result in the form of dataframe, you can cast it like below
result = df[['Field A', 'Field B']].apply(lambda item: item['Field A'].endswith(item['Field B'] + '.pdf'), axis=1)
result = pd.DataFrame(result) # You can add your optional params, column names for example
Concatenate two columns excepting strings from a list_pandas
Given:
words sentence
0 unknown This is a new paint
1 brown This is a new item
2 for sale The product is new
Doing:
restricted = ['not present', 'for sale', 'unknown']
mask = df.words.str.contains('|'.join(restricted))
df['output'] = df.sentence.where(mask, df.sentence + ' ' + df.words)
print(df)
Output:
words sentence output
0 unknown This is a new paint This is a new paint
1 brown This is a new item This is a new item brown
2 for sale The product is new The product is new
How to concatenate two columns consisting of text values i.e, string in Jupyter Lab?
Try this:
import pandas as pd
#create dataframe
df = pd.DataFrame()
df['col1'] = ['a','b','c']
df['col2'] = ['d','e','f']
#new column
df['new_col'] = df['col1'] + df['col2']
Related Topics
How to Check If All Elements of a List Match a Condition
Adding Days to a Date in Python
Finding Local Maxima/Minima with Numpy in a 1D Numpy Array
How to Check If the String Is Empty
How to .Decode('String-Escape') in Python 3
Slicing a List in Python Without Generating a Copy
Python Pandas Insert List into a Cell
Determine Function Name from Within That Function (Without Using Traceback)
The 'Is' Operator Behaves Unexpectedly with Non-Cached Integers
Python 3 Importerror: No Module Named 'Configparser'
How to Use Xpath with Beautifulsoup
Determining Application Path in a Python Exe Generated by Pyinstaller
How to Convert a Utc Datetime to a Local Datetime Using Only Standard Library
How to Delete Rows from a Pandas Dataframe Based on a Conditional Expression
Prepend Line to Beginning of a File
Post-Install Script with Python Setuptools
Access a Function Variable Outside the Function Without Using "Global"