Home > OS >  Getting index and dtypes when getting a list from a column
Getting index and dtypes when getting a list from a column

Time:04-15

I have a dataframe with two columns and I have a statement that I want to fill with the dataframe column values, so I can return a list will all the statements.

I have the following dataframe:

d = {'col1': ['john', 'leo', 'maria', 'zack'], 'col2': ['14','13','45','2']}
df = pd.DataFrame(data=d, index=[0, 1, 2, 3])

I have the following statement:

str = "Hello my name {} and I have {} years old"

So I can get my final output:

["Hello my name john and I have 14 years old", "Hello my name leo and I have 13 years old", "Hello my name maria and I have 45 years old", "Hello my name zack and I have 2 years old"]

My code is the following one:

import pandas as pd
d = {'col1': ['john', 'leo', 'maria', 'zack'], 'col2': ['14','13','45','2']}
df = pd.DataFrame(data=d, index=[0, 1, 2, 3])

str = "Hello my name {} and I have {} years old"
df['stt'] = str.format(df['col1'],df['col2'])

print(df['stt'].tolist())

But when I execute I am getting this:

['Hello my name 0     john\n1      leo\n2    maria\n3     zack\nName: col1, dtype: object and I have 0    14\n1    13\n2    45\n3     2\nName: col2, dtype: object years old', 'Hello my name 0     john\n1      leo\n2    maria\n3     zack\nName: col1, dtype: object and I have 0    14\n1    13\n2    45\n3     2\nName: col2, dtype: object years old', 'Hello my name 0     john\n1      leo\n2    maria\n3     zack\nName: col1, dtype: object and I have 0    14\n1    13\n2    45\n3     2\nName: col2, dtype: object years old', 'Hello my name 0     john\n1      leo\n2    maria\n3     zack\nName: col1, dtype: object and I have 0    14\n1    13\n2    45\n3     2\nName: col2, dtype: object years old']

How I can get the above list?

CodePudding user response:

import pandas as pd
d = {'col1': ['john', 'leo', 'maria', 'zack'], 'col2': ['14','13','45','2']}
df = pd.DataFrame(data=d, index=[0, 1, 2, 3])

df['stt'] = df.apply(lambda x: f"Hello my name is {x['col1']} and I am {x['col2']} years old.", axis=1)

print(df['stt'].tolist())

Output:

['Hello my name is john and I am 14 years old.', 'Hello my name is leo and I am 13 years old.', 'Hello my name is maria and I am 45 years old.', 'Hello my name is zack and I am 2 years old.']
  • Related