熊猫将数据写入单独的CSV文件

时间:2020-05-29 09:13:04

标签: python python-3.x pandas

我有一个看起来像这样的数据框

  Name      Location  Date      Time  Open  High   Low  Close  Volume  VWAP  Trades
4   Orange  New York  20200501  15:30:00  5.50  5.85  5.45   5.70    1500  5.73      95
5   Orange  New York  20200501  17:00:00  5.65  5.70  5.50   5.60    1600  5.65      54
6   Orange  New York  20200501  20:00:00  5.80  5.85  5.45   5.81    1700  5.73      41
0    Apple  Minsk     20200504  15:30:00  3.70  3.97  3.65   3.75    1000  3.60      55
1    Apple  Minsk     20200504  17:00:00  3.65  3.95  3.50   3.80    1200  3.65      68
2    Apple  Minsk     20200504  20:00:00  3.50  3.83  3.44   3.60    1300  3.73      71

如何根据“名称”和“位置”列将每一行写入不同的文件?

所需的输出:

位置:“实体\纽约\橙色\ TwoHours.csv”

    Name    Location  Date      Time  Open  High   Low  Close  Volume  VWAP  Trades
4   Orange  New York  20200501  15:30:00  5.50  5.85  5.45   5.70    1500  5.73      95
5   Orange  New York  20200501  17:00:00  5.65  5.70  5.50   5.60    1600  5.65      54
6   Orange  New York  20200501  20:00:00  5.80  5.85  5.45   5.81    1700  5.73      41

位置:“ Entities \ Minsk \ Apple \ TwoHours.csv”

     Name      Location  Date      Time  Open  High   Low  Close  Volume  VWAP  Trades
0    Apple  Minsk     20200504  15:30:00  3.70  3.97  3.65   3.75    1000  3.60      55
1    Apple  Minsk     20200504  17:00:00  3.65  3.95  3.50   3.80    1200  3.65      68
2    Apple  Minsk     20200504  20:00:00  3.50  3.83  3.44   3.60    1300  3.73      71

有人可以帮我吗?我正在使用的当前代码将整个数据帧写入每个文件,而不仅仅是特定的行:

for idx, rows in Dataframe.iterrows():
dest_dir = os.path.join('Entities', rows.Location, rows.Name)
csv_file = os.path.join(dest_dir, 'TwoHours.csv')
if not os.path.exists(csv_file):
    os.makedirs(dest_dir)
    print("Writing .csv's " + str(idx))
    df1.to_csv(csv_file, sep=";", index=False)

1 个答案:

答案 0 :(得分:3)

这里有可能通过DataFrame.groupby对象进行循环,并从元组中解包nameloc,并在必要时创建folder,最后将组写入文件:

for (name, loc), g in Dataframe.groupby(['Name','Location']):

    dest_dir = os.path.join('Entities', loc, name)
    csv_file = os.path.join(dest_dir, 'TwoHours.csv')

    if not os.path.exists(csv_file):
        os.makedirs(dest_dir)

    g.to_csv(csv_file, sep=";", index=False)