Python 从现有csv文件创建多个csv文件

Python 从现有csv文件创建多个csv文件,python,pandas,csv,pandas-groupby,Python,Pandas,Csv,Pandas Groupby,我正在尝试获取一个大的csv文件,并为两列的排序编写一个csv文件。我能够从文件中获得两个单独的唯一值,以便能够知道需要创建哪些csv文件。 Ex数据: 我想创建一个csv文件“C-GRAD-FILL 09-22-18.csv”,其中包含与这两个值匹配的所有数据。我无法决定如何遍历这两个值的数据 def readData(fileName): df = pd.read_csv(fileName,index_col=False, names+['Number','Northing','Ea

我正在尝试获取一个大的csv文件,并为两列的排序编写一个csv文件。我能够从文件中获得两个单独的唯一值,以便能够知道需要创建哪些csv文件。
Ex数据:

我想创建一个csv文件“C-GRAD-FILL 09-22-18.csv”,其中包含与这两个值匹配的所有数据。我无法决定如何遍历这两个值的数据

def readData(fileName):
    df = pd.read_csv(fileName,index_col=False, names+['Number','Northing','Easting','Elevation','Description','Layer','Date'],parse_dates=['Date'] )
    ##Layers here!!!
    layers = df['Layer'].unique()
    ##Dates here!!! AS DATETIME OBJECTS!!!!
    dates = df['Date'].map(lambda t: t.date()).unique()
    ##Sorted in order
    sortedList = df.sort_values(by=['Layer','Date'])

您可以使用
GroupBy
对象。首先确保您的日期采用正确的字符串格式:

df['Date'] = pd.to_datetime(df['Date']).dt.strftime('%m-%d-%y')
要输出所有文件,请迭代
GroupBy
对象:

for (layer, date), group in df.groupby(['Layer', 'Date']):
    group.to_csv(f'{layer} {date}.csv', index=False)
或者,对于一个特定的组合:

layer = 'C-GRAD-FILL'
date = '09-22-18'
g = df.groupby(['Layer', 'Date'])

g.get_group((layer, date)).to_csv(f'{layer} {date}.csv', index=False)

@Abhi,在我的示例中,我们明确地将其定义为一个字符串:
date='09-22-18'
。但是如果您从一个
pd.Timestamp
对象开始,您可以轻松地切换到字符串,例如
date=my_Timestamp.strftime(“%m-%d-%y”)
。jpp的工作非常好!现在,我需要弄清楚在编写csv时如何删除最后两列。直到现在我才意识到它们是不必要的。
layer = 'C-GRAD-FILL'
date = '09-22-18'
g = df.groupby(['Layer', 'Date'])

g.get_group((layer, date)).to_csv(f'{layer} {date}.csv', index=False)