简体   繁体   English

有没有办法在循环中更快地更改 DataFrame?

[英]Is there a way to make changing DataFrame faster in a loop?

    for index, row in df.iterrows():
        print(index)

        name = row['name']
        new_name = get_name(name)
        row['new_name'] = new_name

        df.loc[index] = row

In this piece of code, my testing shows that the last line makes it quite slow, really slow.在这段代码中,我的测试表明最后一行让它变得非常慢,非常慢。 It basically insert a new column row by row.它基本上逐行插入一个新列。 Maybe I should store all the 'new_name' into a list, and update the df outside of the loop?也许我应该将所有“new_name”存储到一个列表中,并在循环之外更新 df?

Use Series.apply for processing function for each value of column, it is faster like iterrows :使用Series.apply为每个列值处理 function,它像iterrows一样快:

df['new_name'] = df['name'].apply(get_name)

If want improve performance then is necessary change function if possible, but it depends of function.如果要提高性能,则有必要尽可能更改 function,但这取决于 function。

df['new_name'] = df.apply(lambda x: get_name(x) if x.name == 'name' else x)

.apply isn't a best practice, however I am not sure there is a better one here. .apply不是最佳做法,但我不确定这里是否有更好的做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使这个不断变化的数据帧更快? - how to make this changing dataframe faster? 当使用 dataframe 以使其更快时,另一种编写循环的方法和 if 在 python 中 - Alternative way of writing for loop and if in python when working with a dataframe to make it faster Python:是否有更快的方法在 for 循环中过滤 dataframe - Python: Is there a faster way to filter on dataframe in a for loop Python - 在数据框中运行 for 循环的更快方法 - Python - faster way to run a for loop in a dataframe 如何使 for 循环在大型 pandas 数据帧上运行得更快 - How to make a for loop run faster on a large pandas dataframe 如何使一个巨大的循环检查数据帧中的条件在mac中运行得更快 - How to make a huge loop for checking condition in dataframe run faster in mac 为非常大的 dataframe 列表运行 for 循环的更快方法 - faster way to run a for loop for a very large dataframe list 与for循环相比,选择数据帧不同部分的方法更快? - Faster way to select different sections of dataframe than a for loop? 寻找一种比for循环更快的方法来搜索和附加带有熊猫的DataFrame - Looking for a faster way than for-loop to search and append DataFrame with Pandas 在多个条件下在 For 循环中过滤 pandas DataFrame 的更快方法 - Faster way to filter pandas DataFrame in For loop on multiple conditions
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM