从循环创建数据框

时间:2019-11-12 00:20:44

标签: python pandas

我有一个循环运行3次,每次循环产生4个值,例如在下面。

for i in range(0, 3):
    val1 = something
    val2 = something
    val3 = something
    val4 = something

从此循环中,如何创建尺寸为(3x4)的数据框,如下所示?

val1  val2  val3  val4
2     4     5     42
12    23    54    65 
4     12    2     89

2 个答案:

答案 0 :(得分:2)

data = []
for i in range(0, 3):
    val1 = something
    val2 = something
    val3 = something
    val4 = something
    data.append([val1, val2, val3, val4])
df = pd.DataFrame(data, columns=['val1', 'val2', 'val3', 'val4'])

答案 1 :(得分:1)

您可以从这些列表中创建字典,然后将它们转换为数据框。以下是一个示例:

import pandas as pd
example_dict = {'val1':val1,'val2':val2,'val3':val3,'val4':val4}
df = pd.DataFrame(example_dict)

现在您的df如您所愿。

如果您想一次完成所有这些操作,我会做一些不同的事情:

import pandas as pd
example_dict = {'val1':[],'val2':[],'val3':[],'val4':[]}
for i in range(0,3):
    example_dict['val1'].append(something)
    example_dict['val2'].append(something)
    example_dict['val3'].append(something)
    example_dict['val4'].append(something)
df = pd.DataFrame(example_dict)