I needed to add single quotes around each item for 2 different columns in a pandas dataframe. One column is has integer values, the other has string values. Then I wanted to put the items with single quotes around them into a new column.
I tried multiple suggestions on stackoverflow using a for loop with numpy's savetxt method. (I don't need to use numpy) I tried Regex. Couldn't get it to exactly work.
import pandas as pd
import numpy as np
data = {"id": [101, 102, 103, 104, 105],
"person": ['Ty', 'Al', 'Lou', 'Tao', 'Mick']}
df = pd.DataFrame(data)
id_in_quotes=[] #Wanted to put the new items with single quotes into an empty list and put into a new column
person_in_quotes=[] #Wanted to put the new items with single quotes into an empty list and put into a new column
for x in df: #DOES NOT WORK
np.savetxt('text.txt',x, fmt='%r') #DOES NOT WORK
x.append(id_in_quotes)#DOES NOT WORK
In the end, wanted to see 4 columns: id, person, id_with_quotes, person_with_quotes. Columns id and person remain the same. Columns id_with_quotes, person_with_quotes are id and person with each item wrapped in single quotes.
You could achieve this using DataFrame.applymap and DataFrame.merge like this:
df_new = (df.merge(
df.astype(str).applymap(lambda x: "'" + x + "'"),
left_index=True, right_index=True,
suffixes=('', '_with_quotes')))
print(df_new)
id person id_with_quotes person_with_quotes
0 101 Ty '101' 'Ty'
1 102 Al '102' 'Al'
2 103 Lou '103' 'Lou'
3 104 Tao '104' 'Tao'
4 105 Mick '105' 'Mick'
You could do something like this if I'm reading your question right. Basically going through each column and adding quotation marks to the start and end of each item in the column. Convert to str both cases just to be safe.
import pandas as pd
data = {"id": [101, 102, 103, 104, 105],
"person": ['Ty', 'Al', 'Lou', 'Tao', 'Mick']}
df = pd.DataFrame(data)
df['id_w_quotes'] = df['id'].apply(lambda x: "'" + str(x) + "'")
df['person_w_quotes'] = df['person'].apply(lambda x: "'" + str(x) + "'")
df.head()
Which gives this output
id person id_w_quotes person_w_quotes
0 101 Ty '101' 'Ty'
1 102 Al '102' 'Al'
2 103 Lou '103' 'Lou'
3 104 Tao '104' 'Tao'
4 105 Mick '105' 'Mick'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With