I am trying to do a row-by-row print of a Dataframe with pandas.
the dataframe is
df = pd.DataFrame(cursor.fetchall())
and if do print(df) show this
id name stock
0 1 Fruit 8
1 2 Meet 10
2 3 Fish 30
3 4 Cake 20
my intention is to make a for and inside something like this
for ???? :
print(f"the column {id_column_name} is {id_row} and {name_column_name} {name_row} have {name_column_stock} {stock_row} ")
and print
The column id is 1 and name Fruit have stock 8
The column id is 2 and name Meet have stock 10
The column id is 3 and name Fish have stock 30
The column id is 4 and name Cake have stock 20
Thanks!
CodePudding user response:
One way that I accomplished this is using the following:
def f(id_, name, stock, cols):
print(f"The column {cols[0]} is {id_} and {cols[1]} {name} have {cols[2]} {stock}")
for x, y, z in zip(df['id'], df['name'], df['stock']):
f(x, y, z, df.columns)
I iterated through the zipped columns and applied a function prints out the desired output by taking in that information and the column names.
Output:
The column id is 1 and name Fruit have stock 8
The column id is 2 and name Meet have stock 10
The column id is 3 and name Fish have stock 30
The column id is 4 and name Cake have stock 20
CodePudding user response:
Using df.iterrows():
import io
import pandas as pd
string = string = """id name stock
1 Fruit 8
2 Meet 10
3 Fish 30
4 Cake 20
"""
data = io.StringIO(string)
df = pd.read_csv(data, sep="\s ") # Load df from the data string
for row in df.iterrows():
print(f'The column id is {row[1]["id"]} and name {row[1]["name"]} have stock {row[1]["stock"]}')
We get this output:
The column id is 1 and name Fruit have stock 8
The column id is 2 and name Meet have stock 10
The column id is 3 and name Fish have stock 30
The column id is 4 and name Cake have stock 20
CodePudding user response:
Thanks for the answers.
I was looking for a way to use the same function with different dataframes, without having to know the names of the columns. With that form I have to know them to write the print
Isn't there a way to extract that information without knowing the names?