在for循环中构建pandas数据帧

时间:2015-04-26 21:54:51

标签: for-loop pandas dataframe

我有一个for循环,它迭代数据帧并计算两条信息:

for id in members['id']
    x = random_number_function()
    y = random_number_function()

我希望将id,x和y存储在每次构建一行的数据帧中,每次传递for循环。

1 个答案:

答案 0 :(得分:4)

以下是使用dict构建数据框的示例:

dict_for_df = {}
for i in ('a','b','c','d'):    # Don't use "id" as a counter; it's a python function
    x = random.random()        # first value
    y = random.random()        # second value
    dict_for_df[i] = [x,y]     # store in a dict
df = pd.DataFrame(dict_for_df) # after the loop convert the dict to a dataframe