簡體   English   中英

熊貓數據框返回列標題鏈接到每一行的數據值

[英]Pandas dataframe return column header linked to data value for each row

我正在使用熊貓讀取所有CSV文件,然后將行插入數據庫中。 我將使用SQLAlchemy進行此操作。

我將不知道標題名稱或大小,因此它必須是動態的。 假設數據庫規則將確保數據有效性。

我正在嘗試將列標題映射到每個數據值。 參見下面我當前的數據框:

  Example 1 Example 2 Example 3 Example 4
        Cat       Dog     Mouse     Horse
        Cow       Ant       Pig  Elephant

這是我想要的輸出列表:

Example 1=Cat, Example 2=Dog, Example 3=Mouse, Example 4=Horse
Example 1=Cow, Example 2=Ant, Example 3=Pig, Example 4=Elephant

我嘗試使用zip和下面的代碼進行iterrows

    for index, data in df.iterrows():
        mylist.append(data.values)

    myzip = zip(columns, mylist)

    for z in myzip:
        print(z)

但這會為多個值產生一個列標題,如下所示:

('Example 1', array(['Cat', 'Dog', 'Mouse', 'Horse'], dtype=object))
('Example 2', array(['Cow', 'Ant', 'Pig', 'Elephant'], dtype=object))

任何幫助將不勝感激,因為不確定我需要使用什么功能。 我知道to_sql但是我需要為每行創建一個插入語句。 謝謝

@giser_yugang可以找到理想的解決方案。 Pandas具有內置的DataFrame.to_dict(orient='dict') ,該方法可以轉換數據幀並返回字典,在其中可以使用參數orient自定義鍵值對。
“東方”之中的“記錄”給出了您想要的結果。

因此,您的數據框:

數據幀

使用后:

df.to_dict(orient='records')

得到:

[{'Example 1': 'Cat',
  'Example 2': 'Dog',
  'Example 3': 'Mouse',
  'Example 4': 'Horse'},
 {'Example 1': 'Cow',
  'Example 2': 'Ant',
  'Example 3': 'Pig',
  'Example 4': 'Elephant'}]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM