【问题标题】:Pandas: faster string operations in dataframesPandas:数据帧中更快的字符串操作
【发布时间】:2022-11-28 17:37:11
【问题描述】:

我正在开发一个 python 脚本,它从数据库中读取数据并将这些数据保存到 .csv 文件中。 为了正确保存它,我需要转义不同的字符,例如\r\n\n。 这是我目前的做法:

首先,我使用read_sqlpandas 函数从数据库中读取数据。

import pandas as pd

df = pd.read_sql(
    sql = 'SELECT * FROM exampleTable',
    con = SQLAlchemyConnection
)

我得到的表有不同类型的值。

然后,脚本更新获得的数据框,将每个字符串值更改为原始字符串。 为了实现这一点,我使用了两个嵌套的 for 循环来处理每个值。

def update_df(df)
    for rowIndex, row in df.iterrows():
        for colIndex, values in row.items():
           if isinstance(df[rowIndex, colIndex], str):
               df.at[rowIndex, colIndex] = repr(df.at[rowIndex, colIndex])
    return df

但是,我需要详细说明的数据量很大(超过 100 万行,超过 100 列)并且需要数小时。

我需要的是一种以更快的方式创建 csv 文件的方法。

先感谢您。

【问题讨论】:

    标签: python pandas performance csv


    【解决方案1】:

    如果你真的有混合类型,你最好使用 applymap

    df = df.applymap(lambda x: repr(x) if isinstance(x, str) else x)
    

    如果您可以识别字符串列,则使用 apply,也许使用 re.escape?:

    str_cols = ['col1', 'col2']
    df[str_cols] = df[str_cols].apply(re.escape)
    

    【讨论】:

      猜你喜欢
      • 2015-04-03
      • 2012-10-01
      • 2016-03-28
      • 2021-12-18
      • 2017-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-14
      相关资源
      最近更新 更多