Convert list to DataFrame with a specific column (has no name) as a string

Issue

I have a list that I will generate a dataframe with values that have zero on the right like 1.257000, so I need to generate it as a string because as a number these zeros on the right disappear, how should I proceed?

My attempts to identify column 5 (where the values are):

b = [
     ['string 1', 'string 2', 'string 3', 'string 4', 1.257000, 'string 6'],
     ['string 1', 'string 2', 'string 3', 'string 4', 1.546440, 'string 6']
    ]
df = pd.DataFrame(b, dtype={5: str})
df = pd.DataFrame(b, dtype={'5': str})

Current results in Column 5 using only pd.DataFrame(b):

1.257
1.54644

Expected result in Column 5:

1.257000
1.546440

Additional comment after response generated by Zaero Divide:

The numbers in my case can vary in size, it can be 1.230 1.23000 1.2300000, so I can’t format by specifying an equal final number of characters for all after creating the DataFrame.

Solution

The issue here is that the output of b is:

[
 ['string 1', 'string 2', 'string 3', 'string 4', 1.257, 'string 6'], 
 ['string 1', 'string 2', 'string 3', 'string 4', 1.54644, 'string 6']
]

Instantly, those 0s no longer exist.


If you instead had a string/file that looked like:

string 1,string 2,string 3,string 4,1.257000,string 6
string 1,string 2,string 3,string 4,1.546440,string 6

Then it could be read like you want:

file = """string 1,string 2,string 3,string 4,1.257000,string 6
string 1,string 2,string 3,string 4,1.546440,string 6"""

pd.read_csv(StringIO(file), dtype=str, header=None)

Output:

          0         1         2         3         4         5
0  string 1  string 2  string 3  string 4  1.257000  string 6
1  string 1  string 2  string 3  string 4  1.546440  string 6

Answered By – BeRT2me

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published