如何在Python中将for循环转换为apply方法

2024-05-12 13:52:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将这个for循环改为apply方法,因为iterrows/itertuple都太慢了。我有一个相当大的数据集。这可能吗?在

for index, row in df2.iterrows():
    startDateString = str(row['Date'].replace("/",""))
    endDateString = str(row['Date'].replace("/",""))
    zipcode = str(row['Zip'])
    #startDateString = str(startDate)
    #endDateString = str(endDate)
    print("zip: " + "%s" %zipcode + ", daterange: " + startDateString + " - " + endDateString )

Tags: 数据方法infordateindexreplacerow
2条回答

apply()是pandas库中速度最慢的方法之一。您可以对str属性调用执行相同的操作。 你不需要创建所有的变量。在

    df2['new_column'] = f"""zip: {df2.Zip}, daterange: {df2['Date'].str.replace("/","")} - {df2['Date'].str.replace("/","")}"""
    for x in df2.new_column:
         print(x)

希望这对你的数据有用。在

为什么startDate和endDate是同一列?在

str调用与格式说明符一样是无用的。删除它们会导致:

for index, row in df2.iterrows():
    startDate = row['Date'].replace("/","")
    endDate = row['Date'].replace("/","")
    zipcode = row['Zip']
    print("zip: %s, daterange: %s - %s" % (zipcode, startDate, endDate))

相关问题 更多 >