pandas 在 for 循环中构建熊猫数据框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29884046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:15:59  来源:igfitidea点击:

Build pandas dataframe in for loop

for-looppandasdataframe

提问by Christopher Jenkins

I have a for loop that iterates over a dataframe and calculates two pieces of information:

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

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

I'd like to store id, x and y in a dataframe that is built one row at a time, for each pass through the for loop.

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

回答by iayork

Here's an example of using a dict to build 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