printing data from a for loop to a panda’s dataframe

If you want to create dataframe at the end:

items = ["a", "b", "c", "d", "e","f"]
year = df.sort_values().unique()

result = []
for j, item in enumerate(items):
    groups = df.groupby("year")
    i = 0
    for label, binned_data in groups:
        result.append[year[i], item, binned_data['var1'].sum(), binned_data['var2'].count()]
        i += 1
df = pd.DataFrame(result, columns=["Year", "Label", "Var1_Sum", "Var2_Count"])
print (df)

If you want to update the dataframe within the loop:

items = ["a", "b", "c", "d", "e","f"]
year = df.sort_values().unique()

df = pd.DataFrame(columns=["Year", "Label", "Var1_Sum", "Var2_Count"])
for j, item in enumerate(items):
    groups = df.groupby("year")
    i = 0
    for label, binned_data in groups:
        result = [year[i], item, binned_data['var1'].sum(), binned_data['var2'].count()]
        df = pd.DataFrame(result, columns=["Year", "Label", "Var1_Sum", "Var2_Count"]).append(df, ignore_index=True)
        print (df)
        i += 1

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top