相关疑难解决方法(0)

pandas:按二级索引的范围切片MultiIndex

我有一个像这样的MultiIndex系列:

import numpy as np
import pandas as pd

buckets = np.repeat(['a','b','c'], [3,5,1])
sequence = [0,1,5,0,1,2,4,50,0]

s = pd.Series(
    np.random.randn(len(sequence)), 
    index=pd.MultiIndex.from_tuples(zip(buckets, sequence))
)

# In [6]: s
# Out[6]: 
# a  0    -1.106047
#    1     1.665214
#    5     0.279190
# b  0     0.326364
#    1     0.900439
#    2    -0.653940
#    4     0.082270
#    50   -0.255482
# c  0    -0.091730
Run Code Online (Sandbox Code Playgroud)

我想得到s ['b']值,其中第二个索引(' sequence')在2到10之间.

在第一个索引上切片工作正常:

s['a':'b']
# Out[109]: 
# bucket  value
# a       0        1.828176
#         1        0.160496
#         5        0.401985 …
Run Code Online (Sandbox Code Playgroud)

python pandas

24
推荐指数
3
解决办法
3万
查看次数

通过MultiIndex级别或子级切片pandas DataFrame

受到这个答案的启发以及对这个问题缺乏简单的回答,我发现自己写了一些语法糖,让生活更容易通过MultiIndex级别进行过滤.

def _filter_series(x, level_name, filter_by):
    """
    Filter a pd.Series or pd.DataFrame x by `filter_by` on the MultiIndex level
    `level_name`

    Uses `pd.Index.get_level_values()` in the background. `filter_by` is either
    a string or an iterable.
    """
    if isinstance(x, pd.Series) or isinstance(x, pd.DataFrame):
        if type(filter_by) is str:
            filter_by = [filter_by]

        index = x.index.get_level_values(level_name).isin(filter_by)
        return x[index]
    else:
        print "Not a pandas object"
Run Code Online (Sandbox Code Playgroud)

但是,如果我知道熊猫开发团队(我开始,慢慢地!)已经有一个很好的方法来做到这一点,我只是不知道它是什么!

我对吗?

python pandas

11
推荐指数
3
解决办法
1万
查看次数

Plotly Dash 数据表中的可点击超链接

有几个类似的问题我将在本文中引用,但我有一个DataTable带有列的破折号,我想将其制作为可单击的超链接。该表基本上如下所示:

Date                        Ticket ID           Work Order           Link (s)
2018-08-30 22:52:25         1444008             119846184            google.com/woNum=119846184
2021-09-29 13:33:49         1724734             122445397, 122441551 google.com/woNum=122445397, google.com/woNum=122441551
Run Code Online (Sandbox Code Playgroud)

如果没有超链接,我将通过 Pandas 数据框以及 Dash 的数据和列引用创建表,DataTable如下所示:

# works fine
searchFrame = searchFrame.drop(columns=['ContentNoStop'])
columns = [{'name': col, 'id': col} for col in searchFrame.columns]
Run Code Online (Sandbox Code Playgroud)

链接是通过以下方式创建的:

woLink = r'http://corp.com/uniqueid='

df['WO Link'] = df['Work Order'].str.replace('(\d+)', rf'{woLink}\1')

crLink = r'http://corp.com/uniqueid='
        
df['Ticket Link'] = crLink + df['Ticket ID'].astype(str)
Run Code Online (Sandbox Code Playgroud)

现在,根据Plotly 论坛的这个问题,我进行了编辑以适合我的:

columns = [
        {'name': col, 'id': col} 
for col in searchFrame.loc[
                :, …
Run Code Online (Sandbox Code Playgroud)

python plotly-dash

5
推荐指数
1
解决办法
8574
查看次数

标签 统计

python ×3

pandas ×2

plotly-dash ×1