Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从多索引数据帧中选择特定列?_Python_Pandas_Pivot_Multi Index - Fatal编程技术网

Python 如何从多索引数据帧中选择特定列?

Python 如何从多索引数据帧中选择特定列?,python,pandas,pivot,multi-index,Python,Pandas,Pivot,Multi Index,播放kaggle啤酒评论数据集 如何选择这些数据透视表结果?我的最终目标是在两列之间进行计算: (review_overall, mean) minus (review_taste, mean) 有什么想法吗?谢谢 有几个选项可用于从多索引中选择特定结果: # Setup df = pd.DataFrame(np.arange(9).reshape(3, 3)) df.columns = [['A', 'A', 'B'], ['a', 'b', 'c']] df A B

播放kaggle啤酒评论数据集

如何选择这些数据透视表结果?我的最终目标是在两列之间进行计算:

(review_overall, mean) minus (review_taste, mean)

有什么想法吗?谢谢

有几个选项可用于从多索引中选择特定结果:

# Setup
df =  pd.DataFrame(np.arange(9).reshape(3, 3))
df.columns = [['A', 'A', 'B'], ['a', 'b', 'c']]
df

   A     B
   a  b  c
0  0  1  2
1  3  4  5
2  6  7  8 

直接选择

df[('A', 'a')]

0    0
1    3
2    6
Name: (A, a), dtype: int64
通过
loc

df.loc[:, ('A', 'a')]
# or 
# df.loc(axis=1)[('A', 'a')]  

0    0
1    3
2    6
Name: (A, a), dtype: int64
还有
xs

df.xs(('A', 'a'), axis=1)

0    0
1    3
2    6
Name: (A, a), dtype: int64
所有这些情况下的想法都是传递一个字符串元组,分别表示第一级和第二级(列索引有两级)。在你的情况下,这看起来像

review_stat_by_beer[('review_appearance', 'count')]

有更多的方法,但这些是最好的。

试试
review\u stat\u by\u beer[('review\u外观','count')]
!谢谢大家!@cs95想发个帖子让我投你的票吗?
df.loc[:, ('A', 'a')]
# or 
# df.loc(axis=1)[('A', 'a')]  

0    0
1    3
2    6
Name: (A, a), dtype: int64
df.xs(('A', 'a'), axis=1)

0    0
1    3
2    6
Name: (A, a), dtype: int64
review_stat_by_beer[('review_appearance', 'count')]