簡體   English   中英

如何從我的 python 代碼中創建單個 Dataframe 代碼,為 for 循環的每次迭代生成字典?

[英]How can I create a single Dataframe out of my python code that generates a dictionary for each iteration of a for loop?

我的 for 循環生成大約 80 個單獨的字典:

 {'X: 0.81, 'y': 1.1, 'z': 0.5469} {'X: 0.8, 'y': 1.1, 'z': 0.5464} {'X: 0.79, 'y': 1.1, 'z': 0.5461} {'X: 0.78, 'y': 1.1, 'z': 0.546} But I simply want to send each of those dictionary values as a row in a single data frame with the >dataframe header is equal to the key: xyz 0.81 1.1 0.5469 0.8 1.1 0.5464 0.79 1.1 0.546 0.78 1.1 0.546

創建字典列表

rows = [
  {'X: 0.81, 'y': 1.1, 'z': 0.5469},
  {'X: 0.8,  'y': 1.1, 'z': 0.5464},
  {'X: 0.79, 'y': 1.1, 'z': 0.5461},
  {'X: 0.78, 'y': 1.1, 'z': 0.546}
]

然后從他們創建一個 DataFrame

import pandas as pd
df = pd.DataFrame(rows)

如果您關心性能,最好先創建列表,然后再創建 DataFrame。 您可以先創建 DataFrame 並向其中添加行,但這會更慢,因為它每次都會創建一個新的 DataFrame 並復制所有內容。

暫無
暫無

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

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