从排列表创建数据帧,并遍历它
问题描述:
注 - 我问这个问题,假设我的问题是与数据帧的构造,但实际上我的问题是与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']等于“生日快乐”。
答
df_iter
包含(索引行)作为一个元组,只得到该行,试试这个:
f_index, frow = df_iter.next()
答
你的frow
变量是一个元组,你称它为字典,如果我是你,我会调试它以知道frow
的值是多少。
答
以下为我的作品,如果你只是想在第一行,然后使用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值,第三,什么是“专长”列?它在你的代码中无处? – EdChum
我期望的值在assertEqual函数中,我假定熟悉单元测试。用短语vs专长的错字...感谢您的支持! – Selah