【问题标题】:DataFrame from jagged array来自锯齿状数组的数据帧
【发布时间】:2016-11-12 21:13:33
【问题描述】:

我有一个如下所示的数据集:

date = ['01/01/2001','02/01/2001']
countries = [['US', 'UK', 'AU'],['CN']]

所以基本上数据应该是这样的:

def flatten(array):
    return sum(array,[])
pd.DataFrame({'date': flatten([[date[0]]*3, [date[1]]]), 'country': flatten(countries)})
# Which Returns:
    country date
0   US  01/01/2001
1   UK  01/01/2001
2   AU  01/01/2001
3   CN  02/01/2001

上述方法似乎是一种低效的实现方式。 datecountries 数组的长度完全相同。基本上date需要重复子数组的长度。

在 Pandas 中是否有一种优雅的方式来执行此操作?还是我需要像我所做的那样对数组进行预处理?

【问题讨论】:

    标签: python list pandas list-comprehension


    【解决方案1】:

    试试我的 1-liner:

    df = pd.DataFrame(list(chain(*[list(product([x],y)) for x, y in zip(date, countries)])), columns= ['date',"countries"])
    

    说明:

    基本上itertools是在这种情况下以更Pythonic的方式解决问题的完美选择:

    from itertools import chain, product
    df = pd.DataFrame(list(chain(*[list(product([x],y)) for x, y in zip(date, countries)])), columns= ['date',"countries"])
    
    df
    Out[56]: 
             date countries
    0  01/01/2001        US
    1  01/01/2001        UK
    2  01/01/2001        AU
    3  02/01/2001        CN
    

    更新:

    更详细的解释

    • 第一步:使用列表推导,zipitertools.productproduct这两个输入列表: [list(product([x],y)) for x, y in zip(date, countries)] Out[59]: [[('01/01/2001', 'US'), ('01/01/2001', 'UK'), ('01/01/2001', 'AU')], [('02/01/2001', 'CN')]]

    • 第 2 步: 使用 itertools.chain() 解压缩/展平 list of lists list(chain(*[list(product([x],y)) for x, y in zip(date, countries)])) Out[60]: [('01/01/2001', 'US'), ('01/01/2001', 'UK'), ('01/01/2001', 'AU'), ('02/01/2001', 'CN')]

    • 第 3 步: 形成DataFrame df = pd.DataFrame(list(chain(*[list(product([x],y)) for x, y in zip(date, countries)])), columns= ['date',"countries"])

    【讨论】:

    • 您能简单描述一下或链接到链和 * 的含义吗?
    • @Sachin_ruk,没问题。我会尽快更新,6分钟后回来。
    【解决方案2】:

    试试这样的:

        DD = []
        for x, y in zip(date, countries):
            for z in y: DD.append([x,z])
    
        pd.DataFrame(DD, columns= (['date',"countries"]))
    
                date countries
        0  01/01/2001        US
        1  01/01/2001        UK
        2  01/01/2001        AU
        3  02/01/2001        CN
    

    【讨论】:

      猜你喜欢
      • 2015-09-23
      • 2020-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-21
      • 2015-07-01
      • 2015-05-06
      • 1970-01-01
      相关资源
      最近更新 更多