I am trying to print values from a data frame in a sentence.
I have a data frame like the one bellow;
Data
Name | age | Sex | |
---|---|---|---|
1 | Tom | 45 | Male |
when i use a line such as;
print('His name is', Data['Name'], 'and he is', Data['age'], 'He is a', Data['Sex'])
the issue is that it prints dtype and other info that isn't needed, this means the printed sentence is not in the correct format.
How can I get around this?
CodePudding user response:
You can unpack a series into variables and use f-string print:
name, age, sex = df.loc[1]
print(f'His name is, {name}, and he is {age}, He is a {sex}.')
Output:
His name is, Tom, and he is 45, He is a Male.
CodePudding user response:
String concatenation is the most primitive way you can do it. In this example, the .at locator is being used to get a single values using their index value and column name. From your code, Data['Name']
accesses the entire Name series, where you really just want a single value. Besides .at, you may also employee .loc or .iloc.
Data = pd.DataFrame({'Name': {1: 'Tom'}, 'age': {1: 45}, 'Sex': {1: 'Male'}})
print('His name is ' Data.at[ 1, 'Name'] ' and he is ' str(Data.at[ 1, 'age']) ' He is a', Data.at[1, 'Sex'] '.')
Output:
His name is Tom and he is 45 He is a Male.
However, I recommend using one of Python's print formatters such as format or f-strings. It's worth noting that if the Age column is of type int, than it must be cast to a string with the concatenation method. But the formatters take care of that for you and manual casting is not needed.
print('His name is {} and he is {}. He is a {}.'.format(Data.at[ 1, 'Name'] , Data.at[ 1, 'age'], Data.at[1, 'Sex']))
Output:
His name is Tom and he is 45. He is a Male.