虽然不是很清楚你想要的目的是什么,但我想Pandas MultiIndex DataFrame 可能对你有帮助。我在下面写了一些简单的代码,希望可以进一步指导您。
import pandas as pd
sites=pd.Series(['New York','Stockholm','Madrid','New York','New York','Madrid','Stockholm','Stockholm','Stockholm','Madrid','New York'])
col2=pd.Series(['Cup','Plate','Cup','Cup','Plate','Cup','Plate','Cup','Cup','Cup','Plate'])
col3=pd.Series(['a','b','a','b','a','b','a','a','b','a','a'])
col4=pd.Series([3,5,2,5,8,9,2,5,3,5,8])
data=pd.DataFrame({'sites':sites,'col2':col2,'col3':col3,'col4':col4})
# You can of course replce all the codes above with Pandas read related functions.
data1 = data.set_index(['sites','col2','col3']) # Set as MultiIndex DataFrame.
data1.loc[('New York'),:] # This will give you all the 'New York' data
data1.loc[('New York','Cup'),:] # This will give you all the 'New York' & 'Cup' data.
# Retrieving all the 'Cup' data is a bit tricky, see the following
idx=pd.IndexSlice
data1.loc[idx[:,'Cup'],:]
输出如下。
# data
sites col2 col3 col4
0 New York Cup a 3
1 Stockholm Plate b 5
2 Madrid Cup a 2
3 New York Cup b 5
4 New York Plate a 8
5 Madrid Cup b 9
6 Stockholm Plate a 2
7 Stockholm Cup a 5
8 Stockholm Cup b 3
9 Madrid Cup a 5
10 New York Plate a 8
# data1
col4
sites col2 col3
New York Cup a 3
Stockholm Plate b 5
Madrid Cup a 2
New York Cup b 5
Plate a 8
Madrid Cup b 9
Stockholm Plate a 2
Cup a 5
b 3
Madrid Cup a 5
New York Plate a 8
# data1.loc[('New York'),:]
col4
col2 col3
Cup a 3
b 5
Plate a 8
a 8
# data1.loc[('New York','Cup'),:]
col4
col3
a 3
b 5
# data1.loc[idx[:,'Cup'],:]
col4
sites col2 col3
New York Cup a 3
Madrid Cup a 2
New York Cup b 5
Madrid Cup b 9
Stockholm Cup a 5
b 3
Madrid Cup a 5
如果您不想看到任何警告并希望保持高性能,您可以使用idx 和显式编码,它们是:
data1.loc[idx['New York',:,:],:]
data1.loc[idx['New York','Cup',:],:]
data1.loc[idx['','Cup',:],:]
下一步是将这些数据选择写入单独的工作表。我对此不是很熟悉,因为我总是将数据写入文本文件。例如,将其中一个写入 csv 文件就像data1.loc[idx['New York','Cup',:],:].to_csv('result.csv',index=False) 一样简单。我建议您搜索所需的功能。
希望这会有所帮助。祝你好运!