Combine Two Columns of Text in Pandas Dataframe

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 combine two columns of text in pandas dataframe

If both columns are strings, you can concatenate them directly:

df["period"] = df["Year"] + df["quarter"]

If one (or both) of the columns are not string typed, you should convert it (them) first,

df["period"] = df["Year"].astype(str) + df["quarter"]

If you need to join multiple string columns, you can use agg:

df['period'] = df[['Year', 'quarter', ...]].agg('-'.join, axis=1)

Where "-" is the separator.

Pandas - combine two columns

it could be quite simple if your example is accurate

df.fillna(0)      #if the blanks are nan will need this line first
df['xy']=df['x']+df['y']

Combine two columns with same name pandas

You could do:

df.T.reset_index().groupby('index').agg(','.join).T

index city country house_number ... road state unit
0 greensboro,7611 us 3200 ... northline ave nc ste

Combine two columns of text with NaN in pandas

>>> data['c']=data['a'].fillna('') + ' ' + data['b'].fillna('')
>>> data
a b c
0 NaN abc abc
1 abc abc abc abc

However, do note that data['c'][0] == ' abc'. You'd have to use .str.strip() to strip off whitespace if needed.

Combine 2 string columns in pandas with different conditions in both columns

There are other categories but I am only interested in cat1

You can use str.split with series.where to add the extention for cat1:

df['code'] = (df['code'].astype(str).add("."+df['fx'].str.split(".").str[-1])
.where(df['category'].eq("cat1"),df['code']))


print(df)

code fx category
0 AXD.R AXDG.R cat1
1 AXF.FE AXDG_e.FE cat1
2 333.R 333.R cat1

Merge two columns of pandas dataframe containing string representation of lists

You don't need convert them to string

data = {'A': [['ABCD'], ['PQRS'], ['LMNOP']], 'B':[['YUIO', 'DFGH'], ['QWERT', 'CVDF', 'WERT'], ['BCLF', 'DASE', 'OPIU', 'RTYU']]}

df = pd.DataFrame(data)

df['B'] = df['A'] + df['B']
print(df)

A B
0 [ABCD] [ABCD, YUIO, DFGH]
1 [PQRS] [PQRS, QWERT, CVDF, WERT]
2 [LMNOP] [LMNOP, BCLF, DASE, OPIU, RTYU]

If it's originally string, you can use .apply(pd.eval) or .apply(ast.literal_eval) to convert it to Python list.

df['A'] = df['A'].astype('str')
df['B'] = df['B'].astype('str')

df['A'] = df['A'].apply(pd.eval)
df['B'] = df['B'].apply(pd.eval)
# or
import ast
df['A'] = df['A'].apply(ast.literal_eval)
df['B'] = df['B'].apply(ast.literal_eval)

df['B'] = df['A'] + df['B']


Related Topics



Leave a reply



Submit