更容易创建pandas多列Dataframe的方法?

时间:2018-01-04 16:50:45

标签: python pandas

现在我创建一个multi-column DataFrame如下:

column1 = ["A","B","C"]
column2 = ["a","b","c"]
tuples = []
for c1 in column1:
    for c2 in column2:
        tuples += [(i1,i2)]
columns = pd.MultiIndex.from_tuples(tuples, names=['Large index', 'Small index'])        
q = pd.DataFrame(index = t, columns = columns )
q.loc[:, ("A","a")] = 1

现在我想知道:是否有更简单的语法来提供相同的内容? 干杯!

编辑:纠正错别字。

1 个答案:

答案 0 :(得分:1)

您可以使用pd.MultiIndex.from_product从多个迭代的笛卡尔积中创建一个MultiIndex

import pandas as pd
pd.DataFrame(columns=pd.MultiIndex.from_product([column1, column2], names=['Large index', 'Small index']))

#Large index    A           B           C
#Small index    a   b   c   a   b   c   a   b   c