Issue
I have the following dframe
and attempted code below.
import pandas as pd
dframe = pd.DataFrame({
'A' : [1,2,3],
'B' : ['Guitar', 'Piccolo', 'Sax']
})
dframe
for item in dframe:
print(f"{"Mary's favorite number is"}{dframe[0]}{"and her favorite instrument is"}{dframe[1]}")
The expected output is a formatted string for each line of the code indicating "Mary's favorite letter is 1 and her favorite instrument is Guitar", "Mary's favorite letter is 2 and her favorite instrument is Piccolo", etc.
However, the code does not seem to produce these results.
Solution
You can use string concatenation. You have to convert column 'A' to string before:
out = "Mary's favorite number is " + dframe['A'].astype(str) + " and her favorite instrument is " + dframe['B']
print(*out, sep='\n')
# Output
Mary's favorite number is 1 and her favorite instrument is Guitar
Mary's favorite number is 2 and her favorite instrument is Piccolo
Mary's favorite number is 3 and her favorite instrument is Sax
Update: to convert out
series to a dataframe, use to_frame
:
out = out.to_frame('colname')
print(out)
# Output
colname
0 Mary's favorite number is 1 and her favorite i...
1 Mary's favorite number is 2 and her favorite i...
2 Mary's favorite number is 3 and her favorite i...
Answered By - Corralien
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.