DavidDash
DavidDash

Reputation: 3

Python - How to iterate through dataframe to append each row

Quick question on how to append dataframe while keeping the same output. Example code is below.

import pandas as pd

df = pd.read_csv('C:\\Blah\\Code1.csv')

Z = {
    df.iloc[0,1]: {df.iloc[0,2]: 100, df.iloc[0,3]: 200, df.iloc[0,4]: 500},
    df.iloc[1,1]: {df.iloc[1,2]: 100, df.iloc[1,3]: 200, df.iloc[1,4]: 500},
    df.iloc[2,1]: {df.iloc[2,2]: 100, df.iloc[2,3]: 200, df.iloc[2,4]: 500},
    df.iloc[3,1]: {df.iloc[3,2]: 100, df.iloc[3,3]: 200, df.iloc[3,4]: 500},
    df.iloc[4,1]: {df.iloc[4,2]: 100, df.iloc[4,3]: 200, df.iloc[4,4]: 500},
    }

print(Z)

The df.iloc corresponds to an excel file, and the output is:

{'Steve': {'Bob': 100, 'Eric': 200, 'Very': 500}, 'Pokemon': {'Yugioh': 100, 'Steve': 200, 'Cool': 500}, 'Save': {'Really': 100, 'Now': 200, 'Stuff': 500}, 'Tons': {'Of': 100, 'Code': 200, 'Filler': 500}, 'Amazing': {'Truly ': 100, 'Incredible': 200, 'Text': 500}}

When I try to run a while loop, I only get the last row (replacing the 0 with a variable) And when I try to input a range into .iloc, I get the "series objects are not mutable" error

How do I modify the code so that I get the exact same output as above, but in many fewer lines (original had 100)

EDIT: Simplified question to only include sample code. EDIT2: While loop code and output.

import pandas as pd

df = pd.read_csv('C:\\Blah\\Code1.csv')

C = 0
while C < 5:
    Z = {
        df.iloc[C,1]: {df.iloc[C,2]: 100, df.iloc[C,3]: 200, df.iloc[C,4]: 500},
        }
    C += 1

print(Z)

Output below: {'Amazing': {'Truly ': 100, 'Incredible': 200, 'Text': 500}}

Upvotes: 0

Views: 129

Answers (1)

Sy Ker
Sy Ker

Reputation: 2190

If you want to modify the data-frame in place;

C = 0
while C < 5:
    df.iloc[C,2] = 100
    df.iloc[C,3] = 200
    df.iloc[C,4] = 500
    C += 1

If you want to have an extra dictionary;

Z = {}
C = 0
while C < 5:
    Z[df.iloc[C,1]] = {df.iloc[C,2]: 100, df.iloc[C,3]: 200, df.iloc[C,4]: 500}
    C += 1

Upvotes: 1

Related Questions