Aniiya0978
Aniiya0978

Reputation: 284

Access datas from pandas dataframe

I have a pandas dataframe

 A           B
Joe         20
Raul        22
James       30

How can i create sentence in the following format

Mark of Joe is 20
Mark of Raul is 22
Mark of James is 30

Upvotes: 0

Views: 138

Answers (2)

Esa Tuulari
Esa Tuulari

Reputation: 169

First we replicate your dataframe

df = pd.DataFrame({'A': ['Joe', 'Raul', 'James'], 'B': [20, 22, 30]})

Then we can make a new column to the datframe containing the sentences you want

df['sentence'] = 'Mark of ' + df.A + ' is ' + df.B.astype(str)

Finally we check that the "sentence" column contains the sentence in the format you wanted

df
A     B     sentence
Joe   20    Mark of Joe is 20
Raul  22    Mark of Raul is 22
James 30    Mark of James is 30

Upvotes: 0

jezrael
jezrael

Reputation: 862406

For Series join values by + with casting to strings numeric column(s):

s = 'Mark of ' + df.A + ' is ' + df.B.astype(str)
print (s)
0      Mark of Joe is 20
1     Mark of Raul is 22
2    Mark of James is 30
dtype: object

If need loop:

for x in df[['A','B']].to_numpy(): #df.to_numpy() if only A,B columns
    print (f'Mark of {x[0]} is {x[1]}')

Mark of Joe is 20
Mark of Raul is 22
Mark of James is 30
    

Upvotes: 3

Related Questions