我刚刚发现了熊猫,它的能力给我留下了深刻的印象。我很难理解如何使用DataFrame和MultiIndex。
我有两个问题:
(1)导出DataFrame
我的问题是:这个数据集
import pandas as pd
import StringIO
d1 = StringIO.StringIO(
"""Gender,Employed,Region,Degree
m,yes,east,ba
m,yes,north,ba
f,yes,south,ba
f,no,east,ba
f,no,east,bsc
m,no,north,bsc
m,yes,south,ma
f,yes,west,phd
m,no,west,phd
m,yes,west,phd """
)
df = pd.read_csv(d1)
# Frequencies tables
tab1 = pd.crosstab(df.Gender, df.Region)
tab2 = pd.crosstab(df.Gender, [df.Region, df.Degree])
tab3 = pd.crosstab([df.Gender, df.Employed], [df.Region, df.Degree])
# Now we export the datasets
tab1.to_excel('H:/test_tab1.xlsx') # OK
tab2.to_excel('H:/test_tab2.xlsx') # fails
tab3.to_excel('H:/test_tab3.xlsx') # fails 我能想到的一个解决办法是改变列(R的方式)。
def NewColums(DFwithMultiIndex):
NewCol = []
for item in DFwithMultiIndex.columns:
NewCol.append('-'.join(item))
return NewCol
# New Columns
tab2.columns = NewColums(tab2)
tab3.columns = NewColums(tab3)
# New export
tab2.to_excel('H:/test_tab2.xlsx') # OK
tab3.to_excel('H:/test_tab3.xlsx') # OK我的问题是:在Pandas中是否有我在文档中遗漏的更有效的方法来做到这一点?
2)选择列
这种新结构不允许在给定变量上选择列(首先是分层索引的优势)。如何选择包含给定字符串(例如'-ba')的列?
P.S:我见过这个问题,它是相关的,但还没有理解提议的答复
发布于 2013-01-15 19:29:30
这看起来像to_excel中的一个bug,目前我建议使用to_csv (这似乎没有显示出这个问题)。
我将其添加为https://github.com/pydata/pandas/issues/2701。
为了回答第二个问题,如果你真的需要使用to_excel.
您可以使用filter只选择包含'-ba'的列。
In [21]: filter(lambda x: '-ba' in x, tab2.columns)
Out[21]: ['east-ba', 'north-ba', 'south-ba']
In [22]: tab2[filter(lambda x: '-ba' in x, tab2.columns)]
Out[22]:
east-ba north-ba south-ba
Gender
f 1 0 1
m 1 1 0https://stackoverflow.com/questions/14341584
复制相似问题