Python 从行列表中创建DataFrame,并对其进行迭代

Python 从行列表中创建DataFrame,并对其进行迭代,python,pandas,Python,Pandas,注意-我问这个问题的前提是我的问题是DataFrame构造函数,但实际上我的问题是iterrows() 我想从一个列表中创建一个数据框,其中每一行都是一个值列表。我尝试了以下方法: multigram_counts = [ ["happy birthday", 23], ["used below", 10], ["frame for", 2] ] df = pd.DataFrame(multigram_counts, columns = ["phrase", "count

注意-我问这个问题的前提是我的问题是DataFrame构造函数,但实际上我的问题是iterrows()

我想从一个列表中创建一个数据框,其中每一行都是一个值列表。我尝试了以下方法:

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")
但我得到了以下错误:

TypeError: tuple indices must be integers, not str

如何修复此问题,使“assertEqual”函数中的两个参数实际上相等?也就是说,我希望frow['phrase']等于“生日快乐”。

您的
frow
变量是一个元组,您将其称为dict,如果我是您,我将调试它以了解
frow
的值是什么

您的
frow
变量是一个元组,您将其称为dict,如果我是您,我会调试它,以了解frow的值

df_iter
包含(索引,行)作为元组,若要仅获取行,请尝试以下操作:

f_index, frow = df_iter.next()

df_iter
将(索引,行)包含为元组,若要仅获取行,请尝试以下操作:

f_index, frow = df_iter.next()

如果您只需要第一行,请使用
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看起来像这样:

In [100]:

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

如果您只需要第一行,请使用
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看起来像这样:

In [100]:

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

你的代码没有什么意义,首先公布你想要的输出是什么,其次你创建的df没有列表中的值,只有一个str值,第三个是'feat'列?它不在代码中??我想要的值在assertEqual函数中,我假设熟悉单元测试。拼写错误与短语vs壮举。。。谢谢你抓住了!你的代码没有什么意义,首先公布你想要的输出是什么,其次你创建的df没有列表中的值,只有一个str值,第三个是'feat'列?它不在代码中??我想要的值在assertEqual函数中,我假设熟悉单元测试。拼写错误与短语vs壮举。。。谢谢你抓住了!