22

I currently have code that reads in an Excel table (image below):

# Read in zipcode input file

us_zips = pd.read_excel("Zipcode.xls")
us_zips

enter image description here

I use the following code to convert the dataframe zip codes into a list:

us_zips = list(us_zips.values.flatten())

When I print us_zips it looks like this:

[10601, 60047, 50301, 10606]

...but I want it to look like this ["10601", "60047", "50301", "10606"]

How can I do that? *Any help is greatly appreciated

EdChum
  • 376,765
  • 198
  • 813
  • 562
PineNuts0
  • 4,740
  • 21
  • 67
  • 112

3 Answers3

28

You can just cast the column dtype using astype(str) and then convert to list using .values.tolist(), this returns a numpy array using .values which has a member function to convert this to a list:

In [321]:
us_zips['zipcode'].astype(str).values.tolist()

Out[321]:
['10601', '60047', '50301', '10606']
EdChum
  • 376,765
  • 198
  • 813
  • 562
10

It worked for me without .values():

list = df[col_name].astype(str).tolist()
Tom Hale
  • 40,825
  • 36
  • 187
  • 242
0

After creating your list you can simply do the following to convert all your list elements to strings:

us_zips = [str(i) for i in us_zips]

Complete code:

df = pd.DataFrame()
df["x"] = [10601, 60047, 50301, 10606]
us_zips = list(df["x"].values.flatten())
print(us_zips)
us_zips = [str(i) for i in us_zips]
print(us_zips)

Results:

[10601, 60047, 50301, 10606]
['10601', '60047', '50301', '10606']