繁体   English   中英

Python - Pandas - 将横截面与 str.contains 结合使用

[英]Python - Pandas - Using Cross-section in conjunction with str.contains

有没有办法使用熊猫的横截面方法

import numpy as np
import pandas as pd
arrays = [np.array(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux']),
          np.array(['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'])]
df = pd.DataFrame(np.random.randn(8, 4), index=arrays)

df.xs('bar',level=0)

结合 str.contains 方法https : //pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html

目标是在特定级别选择数据,但仅基于包含给定字符串的级别。

在这种特定情况下,它将类似于:

df.xs(df.str.contains('ba'),level=0)

在这种特定情况下,它应该返回(这是一个示例,显然在这里,执行 'bar' 或 'ba' 将返回相同的输出)

         0         1         2         3
one -0.148672  1.025935  0.948375 -0.214719
two  0.066008  0.429827  0.621165 -0.534449

boolean indexingget_level_values

df = df[df.index.get_level_values(0).str.contains('ba')]
print (df)
                0         1         2         3
bar one -0.556376 -0.295627  0.618673 -0.409434
    two  0.107020 -1.143460 -0.145909  0.017417
baz one  0.117667 -0.301128  0.880918 -1.027282
    two  2.287448  1.528137 -1.528636  0.052728

细节:

print (df.index.get_level_values(0))
Index(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux'], dtype='object')

print (df.index.get_level_values(0).str.contains('ba'))
[ True  True  True  True False False False False]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM