[英]Python: what is the best way to iterate through a dataset to pass the values into a dict?
[英]What is the best way to iterate through a data frame in Python?
我試圖建立一個基於另一個數據框。 為了構建第二個,我需要遍歷第一個數據幀並對數據進行一些更改並將其插入第二個。 我正在為我的 for 循環使用 namedTuple。
這個循環需要大量時間來處理 2m 行數據。 有沒有最快的方法來做到這一點?
由於通常 pandas dataframe 是建立在列上的,因此它似乎無法提供一種遍歷行的方法。 但是,這是我用於處理 pandas dataframe 中的每一行的方式:
rows = zip(*(table.loc[:, each] for each in table))
for rowNum, record in enumerate(rows):
# If you want to process record, modify the code to process here:
# Otherwise can just print each row
print("Row", rowNum, "records: ", record)
順便說一句,我仍然建議您尋找一些 pandas 方法來幫助您處理您的第一個 dataframe - 通常會比您自己編寫的更快、更有效。 希望這能有所幫助。
我建議使用內置於 pandas 中的iterrows function。
data = {'Name': ['John', 'Paul', 'George'], 'Age': [20, 21, 19]}
db = pd.DataFrame(data)
print(f"Dataframe:\n{db}\n")
for row, col in db.iterrows():
print(f"Row Index:{row}")
print(f"Column:\n{col}\n")
以上的output:
Dataframe:
Name Age
0 John 20
1 Paul 21
2 George 19
Row Index:0
Column:
Name John
Age 20
Name: 0, dtype: object
Row Index:1
Column:
Name Paul
Age 21
Name: 1, dtype: object
Row Index:2
Column:
Name George
Age 19
Name: 2, dtype: object
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.