2

Top15.head()

I am trying to add comma separators to indicate thousands to my string to a column in a dataframe. Can someone help with format? I do not understand how to do this to an entire column in a dataframe

Top15['PopEst'] = re.sub("(\d)(?=(\d{3})+(?!\d))", r"\1,", "%d" % Top15['PopEst'])
deuwde
  • 75
  • 1
  • 4
python_new_user
  • 233
  • 1
  • 3
  • 9

3 Answers3

4

I think what you are looking for is this:

Top15["PopEst"] = Top15["PopEst"].map(lambda x: "{:,}".format(x))

The "{:,}".format() would work as a thousand separator for a single string/float/int, so you can use map() to apply it to each of the elements in column.

GilZ
  • 6,418
  • 5
  • 30
  • 40
0

I think this will help you.

v= format(12345678, ',d')
print(v)
//12,345,678
Mistalis
  • 17,793
  • 13
  • 73
  • 97
0
Top15['PopEst']=(Top15['Energy Supply']/Top15['Energy Supply per Capita'])
df = Top15[['PopEst']]
df = df.reset_index()

i=0
while(len(df)>i):
    v =str(df.iloc[i]['PopEst']).split('.')

    strr = str(format(int(v[0]), ',d'))+"."+v[1]

    df.iloc[i] = df.iloc[i].replace(df.iloc[i]['PopEst'],strr)

    i = i+1

df.set_index(['Country Name'], inplace=True)