如何在python或大查询上对多个列执行透视操作。最好是大问题
原始数据: 所需转换后数据的外观:如何在python或大查询上对多个列执行透视操作。最好是大问题,python,pandas,google-bigquery,pivot,transpose,Python,Pandas,Google Bigquery,Pivot,Transpose,原始数据: 所需转换后数据的外观: 我在python pandas中尝试了melt函数,但我只能在一列上旋转。我肯定我遗漏了一些东西。下面是BigQuery标准SQL execute immediate ( with types as ( select array_to_string(types, ',') values_list, regexp_replace(array_to_string(types, ','), r'([^,]+)', r'"\1&qu
我在python pandas中尝试了melt函数,但我只能在一列上旋转。我肯定我遗漏了一些东西。下面是BigQuery标准SQL
execute immediate (
with types as (
select
array_to_string(types, ',') values_list,
regexp_replace(array_to_string(types, ','), r'([^,]+)', r'"\1"') columns_list
from (
select regexp_extract_all(to_json_string(t), r'"([^""]+)":') types
from (
select * except(Country, Branch, Category)
from `project.dataset.your_table` limit 1
) t
)
), categories as (
select distinct Category
from `project.dataset.your_table`
)
select '''
select Country, Branch, Output, ''' ||
(select string_agg('''
max(if(Category = "''' || Category || '''", val, null)) as ''' || Category )
from categories)
|| '''
from (
select Country, Branch, Category,
type[offset(offset)] Output, val
from `project.dataset.your_table` t,
unnest([''' || values_list || ''']) val with offset,
unnest([struct([''' || columns_list || '''] as type)])
)
group by Country, Branch, Output
'''
from types
);
如果应用于问题中的样本数据,则输出为
请发布数据,而不是图片。如果没有可用的数据,请查看堆栈/取消堆栈和pd.pivot\u表()