【问题标题】:Want to write csv after concatenating连接后想写csv
【发布时间】:2016-01-27 03:20:33
【问题描述】:
import glob
import os
import pandas as pd


os.chdir('E:\in\extracted')

file_list = glob.glob('*.csv')
df_list = []
col_names = ['Year', 'Month', 'Day', 'Hour', 'Temp', 'DewTemp', 'Pressure', 'WinDir', 'WindSpeed',
             'Sky', 'Precip1', 'Precip6', 'ID']


def outfile():
    new_path = r'E:\out\Concatenated.csv'
    if not os.path.exists(new_path):
        os.makedirs(new_path)


for file_name in file_list:
    print(file_name)
    df = pd.read_csv(file_name, header=None)
    df_list.append(df)
concat_df = pd.concat(df_list)
concat_df.columns = col_names
concat_df = pd.DataFrame.to_csv(path_or_buf=outfile()) #Says I need 'Self'

Traceback(最近一次调用最后一次): 文件“C:/Users/Jesse/PycharmProjects/pythonnewtutorial/Concatenate.py”,第 27 行,在 concat_df.to_csv(path_or_buf=outfile()) TypeError: to_csv() 缺少 1 个必需的位置参数:'self'

当我检查the documentation时,它说只需要路径。

有没有办法解决这个问题?

【问题讨论】:

    标签: python-3.x pandas


    【解决方案1】:

    您将 to_csv 作为数据帧本身的方法调用:

    concat_d.to_csv(outfile()) #Says I need 'Self'
    

    【讨论】:

    • 当我打印(concact_df.head)数据时,谢谢似乎有效,只是出于某种原因将“Concatenated.csv”放入文件夹中。
    • 你的代码应该是if not os.path.exists("E:\out"): os.makedirs("E:\out")
    • 那么就concat_d.to_csv("E:\out\outfile.csv")
    • 你的 outfile 函数没有 return 所以当你把它作为参数时,它将为空
    • 非常感谢您的解释,认为它与outfile有关。
    猜你喜欢
    • 1970-01-01
    • 2016-03-10
    • 2020-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-14
    • 1970-01-01
    相关资源
    最近更新 更多