How to add a full stop to a text please? I am not able to get the desired combined text.
JavaScript
x
18
18
1
# Import libraries
2
import pandas as pd
3
import numpy as np
4
5
# Initialize list of lists
6
data = [['text with a period.', '111A.'],
7
['text without a period', '222B'],
8
['text with many periods...', '333C'],
9
[np.NaN, '333C'],
10
[np.NaN, np.NaN]]
11
12
# Create the pandas DataFrame
13
df = pd.DataFrame(data, columns=['text1', 'text2'])
14
15
combined_df=df.copy()
16
combined_df["combined_text"]=df["text1"].fillna("") + ". " + df["text2"].fillna("") + '.'
17
combined_df
18
Advertisement
Answer
JavaScript
1
6
1
df['combined_text'] = df.text1.where(df.text1.str.endswith('.'), df.text1 + '.').str.cat(
2
df.text2.where(df.text2.str.endswith('.'), df.text2 + '.'),
3
sep=' ',
4
na_rep=''
5
).str.strip().replace('', np.nan)
6
Result:
JavaScript
1
7
1
text1 text2 combined_text
2
0 text with a period. 111A. text with a period. 111A.
3
1 text without a period 222B text without a period. 222B.
4
2 text with many periods 333C text with many periods 333C.
5
3 NaN 333C 333C.
6
4 NaN NaN NaN
7
(this also works for the case when text1
is given and text2
is NaN
)