1

test is a pandas dataframe converted to string.

strtest = (test.to_string())
print strtest

After conversion to string, I have the following output:

This is the first test file     98128612.12
This is the second test file    31236164.15

I am trying to have each line of the string placed into a list and printed out to look like this:

['This is the first test file','98128612.12']
['This is the second test file','31236164.15']

This are my codes when attempting to produce the output above in lists:

testlist = []

for row in strtest.iterrows():
        index, data = row
        testlist.append(data.tolist())

print testlist

However when I run it, I am having this error how do I solve this:

     for row in strtest.iterrows():
 AttributeError: 'unicode' object has no attribute 'iterrows'
Sam T
  • 77
  • 1
  • 7

1 Answers1

1

I think you need:

testlist = test.values.tolist()
print (testlist)
[['This is the first test file', 98128612.12],
 ['This is the second test file', 31236164.15]]

Your code is possible use, but not recommended, because slow:

testlist = []
#change strtest to test DataFrame
for index, data in test.iterrows():
        testlist.append(data.tolist())

print (testlist)
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • I had tried testlist = test.values.tolist() previously however, I am only getting the float values. 'This is the first test file' string wasn't printed at all. The output is as follows: [98128612.12,31236164.15 ] – Sam T Oct 10 '18 at 08:45
  • @SamT - So need `test.astype(str).values.tolist()` ? – jezrael Oct 10 '18 at 08:46
  • thanks for the help but it doesn't seems to be working. Your second solution now generates this: AttributeError: 'Series' object has no attribute 'iterrows' – Sam T Oct 10 '18 at 08:56
  • @SamT - It is Series, you need `for index, data in test.reset_index().iterrows():` – jezrael Oct 10 '18 at 08:58
  • @SamT - and for first solution `testlist = test.reset_index().values.tolist()` – jezrael Oct 10 '18 at 08:58
  • @SamT - here [`reset_index`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.reset_index.html) is used for convert index values to columns - it create DataFrame from Series – jezrael Oct 10 '18 at 08:59