Home > Software design >  Do the Quotation based on having commas and quotation in columns in DataFrame
Do the Quotation based on having commas and quotation in columns in DataFrame

Time:11-11

I have the following data frame contains two columns

A B
22,34 "Book",2
12,40 "Note",6
12 20

I want to check the data frame if columns have commas in between like 22,34 or have something like "Book",2 then put Quotation around them. The final result must be like this :

A B
"22,34" "'Book',2"
"12,40" "'Note',6"
12 20

CodePudding user response:

Just an update on @Joshua's answer. You don't need to loop through all columns, just use df.applymap on the whole DataFrame .

This one line of code does the job aswell.

df = df.applymap(lambda x: x if "," not in x else "\""   x   "\"") 

CodePudding user response:

#starting df
>>> df = pd.DataFrame({'A': {0: '22,34',    1: '12,40',    2: '12'},
                       'B': {0: '"Book",2', 1: '"Note",6', 2: '20'}})
>>> df
       A         B
0  22,34  "Book",2
1  12,40  "Note",6
2     12        20

>>> for column in df.columns:
        df.loc[:,column] = df.loc[:,column].transform(lambda x: 
            x if "," not in x else 
            "\""   x   "\"")
>>> df
         A           B
0  "22,34"  ""Book",2"
1  "12,40"  ""Note",6"
2       12          20

#result df
>>> df.to_dict()
{'A': {0: '"22,34"',    1: '"12,40"',    2: '12'}, 
 'B': {0: '""Book",2"', 1: '""Note",6"', 2: '20'}}
  • Related