For loop 在for循环中构建数据帧

For loop 在for循环中构建数据帧,for-loop,pandas,dataframe,For Loop,Pandas,Dataframe,我有一个for循环,它迭代数据帧并计算两条信息: for id in members['id'] x = random_number_function() y = random_number_function() 我希望将id、x和y存储在一个数据帧中,该数据帧一次构建一行,每次通过for循环。以下是使用dict构建数据帧的示例: dict_for_df = {} for i in ('a','b','c','d'): # Don't use "id" as a coun

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

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

我希望将id、x和y存储在一个数据帧中,该数据帧一次构建一行,每次通过for循环。

以下是使用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

下面是一个使用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

你想一次构建一行数据帧,而不是将信息存储在dict中,然后再将dict转换为数据帧,这有什么原因吗?为什么你不能只做
members['x']=calculate_x(members['id'])
和“y”列?一点也不-我不熟悉dict对象您只需修改
计算
代码以接受一个序列,使其矢量化,但您可以使用任意数量的
np.random.randint
或任何函数生成随机值数组,通常情况下,循环行是没有必要的。有没有理由一次只构建一行数据帧,而不是将信息存储在dict中,然后再将dict转换为数据帧?为什么不能只执行
members['x']=calculate_x(members['id'])
和“y”列?一点也不-我不熟悉dict对象您只需修改
计算
代码以接受一个序列,使其矢量化,但您可以使用任意数量的
np.random.randint
或任何函数生成随机值数组,虽然我的结果被错误地转置了,但通常来说,没有必要循环行。与我使用的df=pd.DataFrame(dict_代表_-df)不同,df=DataFrame.from_-dict(dict_代表_-df,orient='index')或者只使用“pd.DataFrame(dict_代表_-df.T)”-“T”转换数据框架这是可行的,尽管我得到的结果转换方式错误。与我使用的df=pd.DataFrame(dict_表示_-df)不同,df=DataFrame.from_-dict(dict_表示_-df,orient='index')或只使用“pd.DataFrame(dict_表示_-df).T”--“T”转置数据帧