Search code examples
pandasdataframereadlines

Python pandas : dataframe read rows (readlines)


I have a dataframe that was produced by pandas, for example:

d = {'one':[1,1],'two':[2,2], 'three':[3,3]}
i = ['a','b','c']
df = pd.DataFrame(data = d, index = i)
df

        one two three

  a     1   2    3

  b     1   2    3

  c     1   2    3

I now need to read each row with comma separated, I don't want to save to_csv then open it again, any good suggestion?

I am used to something like in python:

for line in df.readlines():
    print line

But I don't know how to connect my ideas now, thanks a lot!


Solution

  • I don't know why you wouldn't want to save and reopen but try this:

    df = df.astype(str)
    separators = pd.DataFrame(', ', df.index, df.columns[:-1])
    separators[df.columns[-1]] = '\n'
    print (df + separators).sum(axis=1).sum()
    
    1, 3, 2
    1, 3, 2
    1, 3, 2