Selah
Selah

Reputation: 8054

Create DataFrame from list of rows, and Iterate Over it

NOTE - I asked this question assuming my issue was with the DataFrame constructor, but actually my issue was with iterrows()

I would like to create a pandas DataFrame from a list a rows, where each row is a list of values. I have tried the following:

multigram_counts = [
    ["happy birthday", 23],
    ["used below", 10],
    ["frame for", 2]
]
df = pd.DataFrame(multigram_counts, columns = ["phrase", "count"])
df_iter = df.iterrows()
frow = df_iter.next()
self.assertEqual(frow['phrase'], "happy birthday")

But I get the following error:

TypeError: tuple indices must be integers, not str

How do I fix this so that both arguments in my "assertEqual" function are indeed equal? That is, I would like frow['phrase'] to equal "happy birthday".

Upvotes: 0

Views: 1430

Answers (3)

EdChum
EdChum

Reputation: 393923

The following works for me, if you just want the first row then use iloc:

In [99]:

multigram_counts = [
    ["happy birthday", 23],
    ["used below", 10],
    ["frame for", 2]
]
df = pd.DataFrame(multigram_counts, columns = ["phrase", "count"])
​
df.iloc[0]['phrase'] == 'happy birthday'
Out[99]:
True

df looks like this:

In [100]:

df
Out[100]:
           phrase  count
0  happy birthday     23
1      used below     10
2       frame for      2

Upvotes: 1

Haifeng Zhang
Haifeng Zhang

Reputation: 31885

df_iter contains (index, row) as a tuple, to get the row only, try this:

f_index, frow = df_iter.next()

Upvotes: 2

gbriones.gdl
gbriones.gdl

Reputation: 536

Your frow variable is a tuple and you are calling it as a dict, if I were you, I would debug it to know what is the value of frow.

Upvotes: 1

Related Questions