Reputation: 35
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)......."
Upvotes: 1
Views: 1234
Reputation: 199
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'
Upvotes: 1
Reputation: 75080
Seems like you just need:
df.astype(str).add(' '+df.columns)
name age dob
0 A name 10 age 20-Jun-1969 dob
Upvotes: 1