将python数据框架导出到google sheets中的树结构中

2024-06-01 05:46:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个数据框:

   Col1   Col2   Col3   Col4
1|  A   | auto | big   | red
2|  A   | moto | big   | red
3|  B   | auto | small | blue
4|  C   | auto | small | green
5|  C   | auto | big   | red
6|  C   | moto | small | blue
7|  C   | moto | small | black

我想以以下形式导出谷歌表单:

    Col1   Col2   Col3    Col4
 1|  A   |      |       |
 2|  A   | auto |       |
 3|  A   | auto | big   |
 4|  A   | auto | big   | red
 5|  A   | moto |       |
 6|  A   | moto | big   |
 7|  A   | moto | big   | red
 8|  B   |      |       |
 9|  B   | auto |       |
10|  B   | auto | small |
11|  B   | auto | small | blue
12|  C   |      |       |
13|  C   | auto |       |
14|  C   | auto | small |
15|  C   | auto | small | green
16|  C   | auto | big   |
17|  C   | auto | big   | red
18|  C   | moto |       |
19|  C   | moto | small |
20|  C   | moto | small | blue
21|  C   | moto | small | black

我曾尝试将数据帧转换成字典,但后来我被困在如何“打印”它的问题上

这是我的密码:

import numpy as np
import pandas as pd
from collections import defaultdict

def get_tree( data ):

    df = data.filter( [ 'Col1', 'Col2', 'Col3', 'Col4' ], axis='columns' )

    d = defaultdict( lambda: defaultdict(list) )

    for row in df.itertuples():
        d[ row[1] ][ row[2] ][ row[3] ].append( row[4] )
        
    return d

有什么提示吗


Tags: 数据importautogreenblueredcol2col3
1条回答
网友
1楼 · 发布于 2024-06-01 05:46:15

与数据帧df类似

  Col1  Col2   Col3   Col4
0    A  auto    big    red
1    A  moto    big    red
2    B  auto  small   blue
3    C  auto  small  green
4    C  auto    big    red
5    C  moto  small   blue
6    C  moto  small  black

这个

length = df.shape[1]
data = {col: [] for col in df.columns}
old_row = tuple('' for _ in range(length))
for row in zip(*[df[col] for col in df.columns]):
    depth = max([i for i in range(length)
                 if all(old_row[j] == row[j] for j in range(i + 1))]
                + [-1])
    for n in range(depth + 1, length):
        for i, col in enumerate(df.columns):
            data[col].append(row[i] if i <= n else '')
    old_row = row

df = pd.DataFrame(data)

为您提供以下数据帧(以及相应的字典data

   Col1  Col2   Col3   Col4
0     A                    
1     A  auto              
2     A  auto    big       
3     A  auto    big    red
4     A  moto              
5     A  moto    big       
6     A  moto    big    red
7     B                    
8     B  auto              
9     B  auto  small       
10    B  auto  small   blue
11    C                    
12    C  auto              
13    C  auto  small       
14    C  auto  small  green
15    C  auto    big       
16    C  auto    big    red
17    C  moto              
18    C  moto  small       
19    C  moto  small   blue
20    C  moto  small  black

这就是你要找的吗

相关问题 更多 >