【问题标题】:How to create a data frame using two lists in Python?如何在 Python 中使用两个列表创建数据框?
【发布时间】:2022-11-22 06:11:48
【问题描述】:
L1 = ['a','b','c','a','b','c']
L2 = ['Cat','Fish','Crow','Dog','Frog','Eagle']

Desired Output 1: D1 = {'a':['Cat','Dog'],
                    'b':['Fish','Frog'],
                    'c':['Crow','Eagle']}

Desired Output 2: DF1 =   A        B        C   
                     Cat      Fish      Crow
                     Dog      Frog      Eagle

我只使用从 a 到 c 作为参考,我在 DataFrame 中有 100 多列。

有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: python pandas list dictionary zip


    【解决方案1】:

    尝试:

    L1 = ["a", "b", "c", "a", "b", "c"]
    L2 = ["Cat", "Fish", "Crow", "Dog", "Frog", "Eagle"]
    
    out = {}
    for a, b in zip(L1, L2):
        out.setdefault(a, []).append(b)
    
    print(out)
    

    印刷:

    {"a": ["Cat", "Dog"], "b": ["Fish", "Frog"], "c": ["Crow", "Eagle"]}
    

    然后你可以这样做:

    out_df = pd.DataFrame(out)
    out_df.columns = out_df.columns.str.upper()
    
    print(out_df)
    

    印刷:

         A     B      C
    0  Cat  Fish   Crow
    1  Dog  Frog  Eagle
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-07
      • 1970-01-01
      • 2021-12-19
      • 2020-03-08
      • 1970-01-01
      • 1970-01-01
      • 2023-02-21
      • 2022-08-11
      相关资源
      最近更新 更多