1

How can I transform rows of Pandas dataframe into list of strings? I want to map each row of data frame into string such as it contains name of column and value of column for selected columns of dataframe:

for example I would like to convert columns B,C,D into list of strings (result) as is shown below:

import pandas as pd
A=[1,2,3,4]
B=[5,6,7,8]
C=[2,3,4,5]
D=[4,5,6,7]
df=pd.DataFrame(data=[A,B,C,D]).transpose()
df.columns=['A','B','C','D']
print df

   A  B  C  D
0  1  5  2  4
1  2  6  3  5
2  3  7  4  6
3  4  8  5  7

result=['B:5,C:2,D:4','B:6,C:3,D:5','B:7,C:4,D:6','B:5,C:2,D:4','B:8,C:5,D:7']
print
print result

['B:5,C:2,D:4', 'B:6,C:3,D:5', 'B:7,C:4,D:6', 'B:5,C:2,D:4', 'B:8,C:5,D:7']

Edit: format of the string does not need to be exactly as in my example as long as it contains column names and values

1 Answer 1

2

Not sure if it is the best way but this will do what you want:

cols = ["B", "C", "D"]
[",".join("{}:{}".format(*t) for t in zip(cols, row)) for _, row in df[cols].iterrows()]

Which will give you:

['B:5,C:2,D:4', 'B:6,C:3,D:5', 'B:7,C:4,D:6', 'B:8,C:5,D:7']
Sign up to request clarification or add additional context in comments.

1 Comment

It does work using python3 but based on your prints you don't seem to be using python3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.