【问题标题】:How to remove decimal point from string using pandas如何使用熊猫从字符串中删除小数点
【发布时间】:2019-03-19 08:04:46
【问题描述】:

我正在读取一个 xls 文件并使用 pyspark 在数据块中转换为 csv 文件。 我的输入数据是 xls 文件中的字符串格式 101101114501700。但是在使用 pandas 将其转换为 CSV 格式并写入 datalake 文件夹后,我的数据显示为 101101114501700.0。我的代码如下。请帮助我为什么我在数据中得到小数部分。

for file in os.listdir("/path/to/file"):
     if file.endswith(".xls"):
       filepath = os.path.join("/path/to/file",file)         
       filepath_pd = pd.ExcelFile(filepath)
       names = filepath_pd.sheet_names        
       df = pd.concat([filepath_pd.parse(name) for name in names])        
       df1 = df.to_csv("/path/to/file"+file.split('.')[0]+".csv", sep=',', encoding='utf-8', index=False)
       print(time.strftime("%Y%m%d-%H%M%S") + ": XLS files converted to CSV and moved to folder"

【问题讨论】:

    标签: python excel python-3.x pandas dataframe


    【解决方案1】:

    我认为读取 excel 时该字段会自动解析为浮点数。之后我会更正它:

    df['column_name'] = df['column_name'].astype(int)
    

    如果您的列包含 Null,则您无法转换为整数,因此您需要先填充 null:

    df['column_name'] = df['column_name'].fillna(0).astype(int)
    

    然后您可以按照您的方式连接并存储它

    【讨论】:

    • 感谢 gigorio 的回复。但我需要将该列放在字符串中,因为在转换为 csv 后,我正在为某些列做 substr。我可以使用 read_excel 的替代解决方案吗?
    • df['column_name'] = df['column_name'].fillna(0).astype(int).astype(str)
    【解决方案2】:

    您的问题与 Spark 或 PySpark 无关。与Pandas有关。

    这是因为 Pandas 会自动解释和推断列的数据类型。由于列的所有值都是数字,Pandas 会将其视为float 数据类型。

    为避免这种情况,pandas.ExcelFile.parse 方法接受一个名为 converters 的参数,您可以通过以下方式告诉 Pandas 特定的列数据类型:

    # if you want one specific column as string
    df = pd.concat([filepath_pd.parse(name, converters={'column_name': str}) for name in names])
    

    # if you want all columns as string
    # and you have multi sheets and they do not have same columns
    # this merge all sheets into one dataframe
    def get_converters(excel_file, sheet_name, dt_cols):
        cols = excel_file.parse(sheet_name).columns
        converters = {col: str for col in cols if col not in dt_cols}
        for col in dt_cols:
            converters[col] = pd.to_datetime
        return converters
    
    df = pd.concat([filepath_pd.parse(name, converters=get_converters(filepath_pd, name, ['date_column'])) for name in names]).reset_index(drop=True)
    

    # if you want all columns as string
    # and all your sheets have same columns
    cols = filepath_pd.parse().columns
    dt_cols = ['date_column']
    converters = {col: str for col in cols if col not in dt_cols}
    for col in dt_cols:
        converters[col] = pd.to_datetime
    df = pd.concat([filepath_pd.parse(name, converters=converters) for name in names]).reset_index(drop=True)
    

    【讨论】:

    • 感谢袁老师的回复。我已经尝试过您的解决方案,但显然 Python 引擎不支持 dtype。您可能有任何其他解决方案,请分享。非常感谢提前
    • 感谢袁,对于一列它工作正常。如果对于多列,那么如何使它成为通用的?
    • 我更新了答案,它将所有工作表合并为一张dataframe,并将所有工作表的所有列转换为string
    • 感谢袁,它适用于数字列,但对于日期(2019-03-19)数据,它会像这样附加 2019-03-19 00:00:00。你能告诉我这是为什么吗?我们可以使用 read_excel 做同样的事情吗?这个可以吗?
    • 您的日期字符串问题是因为 Pandas 自动将日期列转换为 pandas.Timestamp 类型,当您应用转换器(在其上应用 str())时,默认字符串表示 __str__()pandas.Timestamp格式为%Y-%m-%d %H:%M:%S,显示在您的数据中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-21
    • 2023-01-11
    • 2021-01-11
    • 2021-09-25
    • 2017-06-02
    • 2021-08-27
    相关资源
    最近更新 更多