Cobin
Cobin

Reputation: 930

How to modify elements length of pandas dataframe?

I want to change pandas dataframe each element to specified length and decimal digits. Length mean the numbers of charactors. For example, element -23.5556 is 8 charactors length (contain minus and point). I want to modify it to total 6 charactors length containing 2 decimal digits, such as -23.56. If less than 6 charactors ,use space to fill. There is no seperation between each element of new df at last.

name     x                 y           elev     m1      m2 
136 5210580.00000   5846400.000000  43.3    -28.2   -24.2
246 5373860.00000   5809680.000000  36.19   -25     -22.3
349 5361120.00000   5735330.000000  49.46   -24.7   -21.2
353 5521370.00000   5770740.000000  17.74   -26     -20.5
425 5095630.00000   5528200.000000  58.14   -30.3   -26.1
434 5198630.00000   5570740.000000  73.26   -30.2   -26
442 5373170.00000   5593290.000000  37.17   -22.9   -18.3

each columns format requested:

     charactors    decimal digits 
name      3              0
x         14             2
y         14             2
elev       4             1
m1         6             2
m2         6             2

the new df format I wanted:

1365210580.00    5846400.00    43.3-28.2 -24.2
2465373860.00    5809680.00    36.1-25.0 -22.3
3495361120.00    5735330.00    49.4-24.7 -21.2
3535521370.00    5770740.00    17.7-26.0 -20.5
4255095630.00    5528200.00    58.1-30.3 -26.1
4345198630.00    5570740.00    73.2-30.2 -26.0
4425373170.00    5593290.00    37.1-22.9 -18.3

Lastly, save the new df as .dat fixed ascii format. Which tool could do this in pandas?

Upvotes: 1

Views: 406

Answers (2)

piRSquared
piRSquared

Reputation: 294488

You can use string formatting

sf = '{name:3.0f}{x:<14.2f}{y:<14.2f}{elev:<4.1f}{m1:<6.1f}{m2:6.1f}'.format
df.apply(lambda r: sf(**r), 1)

0    1365210580.00    5846400.00    43.3-28.2  -24.2
1    2465373860.00    5809680.00    36.2-25.0  -22.3
2    3495361120.00    5735330.00    49.5-24.7  -21.2
3    3535521370.00    5770740.00    17.7-26.0  -20.5
4    4255095630.00    5528200.00    58.1-30.3  -26.1
5    4345198630.00    5570740.00    73.3-30.2  -26.0
6    4425373170.00    5593290.00    37.2-22.9  -18.3

Upvotes: 1

Vaishali
Vaishali

Reputation: 38415

You need

df.round(2) 

The resulting df

    name    x   y       elev    m1  m2
0   136 5210580 5846400 43.30   -28.2   -24.2
1   246 5373860 5809680 36.19   -25.0   -22.3
2   349 5361120 5735330 49.46   -24.7   -21.2
3   353 5521370 5770740 17.74   -26.0   -20.5
4   425 5095630 5528200 58.14   -30.3   -26.1
5   434 5198630 5570740 73.26   -30.2   -26.0
6   442 5373170 5593290 37.17   -22.9   -18.3

Upvotes: 0

Related Questions