Home > Net >  printing the pandas dataframe column following the string format
printing the pandas dataframe column following the string format

Time:11-14

I have a code to generate the following output

x1 = ['A', 'B', 'C', 'D']
x2 = [',', ',', ',', ',']
test_dataframe = pd.DataFrame()
test_dataframe['id'] = x1
test_dataframe['sep'] = x2
print(test_dataframe[['id','sep']].to_string(index=False))


id sep
 A   ,
 B   ,
 C   ,
 D   ,

However, I would like to let the output of id column follows the following format

id  sep
 'A' ,
 'B' ,
 'C' ,
 'D' ,

How to achieve this kind of result.

CodePudding user response:

You can add the " ' " manually to your id column.

df['id']= "'" df ['id'] "'"

CodePudding user response:

There is no option to temporarily change the printing format as you want for print. Instead, you can add ' to the value as follows:

x1 = ['A', 'B', 'C', 'D']
x2 = [',', ',', ',', ',']
test_dataframe = pd.DataFrame()
test_dataframe['id'] = x1
test_dataframe['sep'] = x2
test_dataframe['id2'] = test_dataframe['id'].apply(lambda x: "'"   x   "'")
print(test_dataframe[['id2', 'sep']].to_string(index=False))

# id sep
#'A'   ,
#'B'   ,
#'C'   ,
#'D'   ,

CodePudding user response:

Another option is using Series.map str.format

test_dataframe['id'] = test_dataframe['id'].map("'{0}'".format)

Output

>>> print(test_dataframe[['id2', 'sep']].to_string(index=False))

  id sep
 'A'   ,
 'B'   ,
 'C'   ,
 'D'   ,
  • Related