For example, your dataframe looks like this:
keywords1 keywords2 keywords3 key1 key2 col2
0 blue red green 1 5 NaN
1 big NaN medium 2 6 3
2 bat ball goal 3 7 0
Now lets assume that you need to add first three columns and add to another column. So,
col_1 = ['keywords1', 'keywords2', 'keywords3']
df["new_col_1"] = df[col_1].apply(lambda x: ''.join(x.dropna()), axis=1)
As I understood that your data contains basically string type data, the above code should work fine. Otherwise, you can convert the columns into string using the.apply(str)
function.
Older Solution:
You can perform the operation and put it in a pandas.core.series.Series
. For example:
df = pd.read_excel('sample_excel.xlsx', engine='openpyxl') df
The output will be:
key1 key2
0 1 5
1 2 6
2 3 7
Now, let's do some operations:
df['key3'] = df['key1'] + df['key1']
df
The output is:
key1 key2 key3
0 1 5 6
1 2 6 8
2 3 7 10
Now save the new dataframe as excel file:
df.to_excel('new_sample.xlsx')
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…