1

I have a dataframe that contains all sort of data -- string,int and date object too.

I already have apiece of code (deal_value(val)) that identifies the type of val and makes it a string. I need to be able to apply that to all the cells in the dataframe I have right now.

After that, I need to concatenate the row value with the row name in the dataframe.

I looked at apply function for both of these but was unable to figure out how to use it in either case


Dataframe Examples:

     name    age    dob
0    A        10    20-Jun-1969

And I want the dataframe to be:

    name         age         dob
0    A name     10 age      20-Jun-1969 dob

My function deal_value would take each cell element and make them good to concatenate into a string, so ultimately I want it to be something like:

"A name, 10 age,20-Jun-1969 AND (row-2) AND (row-3)......."

2 Answers2

1
import pandas

df = pandas.DataFrame({'name': 'A', 'age': 10, 'date_of_birth': '20-Jun-1969'}, index=[0])

for col in list(df.columns): 
    df[col] = df[col].apply(lambda x: ' '.join([str(col), str(x)]))


df.head()

Output

    name     age        date_of_birth
0   name A   age 10     date_of_birth 20-Jun-1969

String Output :


df_to_string = df.to_string(header=False,
                            index=False,
                            index_names=False).split('\n')
vals = [ ', '.join(element.lstrip().rstrip().split('  ')) for element in df_to_string]
vals_str = ' And '.join(vals)

print(vals_str)

Output:

'name A, age 10, date_of_birth 20-Jun-1969 And name B,  age 5, date_of_birth 21-Jun-1969'

Kaies LAMIRI
  • 199
  • 1
  • 8
1

Seems like you just need:

df.astype(str).add(' '+df.columns)

     name     age              dob
0  A name  10 age  20-Jun-1969 dob
anky
  • 74,114
  • 11
  • 41
  • 70
  • Wow this is huge, I like it but the only thing here is that if there are null values you would still stringify them – Kaies LAMIRI Jun 27 '19 at 14:28
  • @KaiesLAMIRI if i understand the question, everything will be `object` dtype? since you are adding the col names anyway..? – anky Jun 27 '19 at 14:30
  • 1
    Yes ! correct but, I mean with this solution you have less flexibility in dealing with non common cases .. but I appreciate your solution btw !! – Kaies LAMIRI Jun 27 '19 at 14:43
  • 1
    @KaiesLAMIRI The OP hasn't specified any non-common cases to be taken care of. i would have taken a different approach then. Anyways, up-voted your's sol. – anky Jun 27 '19 at 14:47
  • 1
    up-voted yours too ! yes I am just talking from a pythonic perspective :) – Kaies LAMIRI Jun 28 '19 at 06:54