我有一个看起来像这样的数据框
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
位置:“实体\明斯克\苹果\ 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)
这是可能的,DataFrame.groupby
使用unpack name
和loc
tuple 逐个对象地循环,如果需要,可以创建folder
s,最后将组写入文件:
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句