在 Python 中遍历数据框的最佳方法是什么?

我试图建立一个基于另一个数据框。为了构建第二个,我需要遍历第一个数据帧并对数据进行一些更改并将其插入到第二个中。我正在为我的 for 循环使用 namedTuple。

这个循环需要大量时间来处理 2m 行数据。有没有最快的方法来做到这一点?


UYOU
浏览 203回答 2
2回答

互换的青春

由于通常 pandas 数据框是建立在列上的,因此它似乎无法提供一种遍历行的方法。但是,这是我用于处理 pandas 数据框中每一行的方式: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 方法 - 通常会比您自己编写更快、更有效。希望这能有所帮助。

米脂

我建议使用pandas内置的iterrows函数。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")上面的输出:Dataframe:     Name  Age0    John   201    Paul   212  George   19Row Index:0Column:Name    JohnAge       20Name: 0, dtype: objectRow Index:1Column:Name    PaulAge       21Name: 1, dtype: objectRow Index:2Column:Name    GeorgeAge         19Name: 2, dtype: object
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python