Reputation: 238
I have a dataframe say df_dt_proc
with 35 columns.
I want to add a column to the dataframe df_dt_proc['procedures']
which should have all the columns concatenated except column at index 0 separated by ,
.
I am able to achieve the result by the following script:
df_dt_proc['procedures'] = np.nan
_len = len(df_dt_proc.columns[1:-1])
for i in range(len(df_dt_proc)):
res = ''
for j in range(_len):
try:
res += df_dt_proc[j][i] + ', '
except:
break
df_dt_proc['procedures'][i] = res
However, there must be a more pythonic way to achieve this.
Upvotes: 1
Views: 249
Reputation: 862511
Use custom lambda function with remove NaN
and None
s and converting to strings, for select all columns without first and last use DataFrame.iloc
:
f = lambda x: ', '.join(x.dropna().astype(str))
df_dt_proc['procedures'] = df_dt_proc.iloc[:, 1:-1].agg(f, axis=1)
Upvotes: 1
Reputation: 71570
Try this with agg
:
df_dt_proc['procedures'] = df_dt_proc[df_dt_proc.columns[1:-1]].astype(str).agg(', '.join, axis=1)
Upvotes: 0