小编Ton*_*ony的帖子

复制 Jupyter Notebook Pandas 数据帧 HTML 打印输出

我正在尝试将 jupyter 在其笔记本中用于 Pandas 数据框的输出复制到 html/css/js,以便 Flask 可以将其jsonify作为 html 返回,然后我将在 AJAX 调用中使用它。

我发现了thisthis,它建议使用 pandas 内置样式功能而不是 CSS hacks,但我正在努力获得所需的功能:

def hover(hover_color="#add8e6"):
    return dict(selector="tr:hover",
                props=[("background-color", "%s" % hover_color)])

styles = [
    hover(),
    dict(selector="th", props=[("font-size", "125%"),
                               ("text-align", "center"),
                               ("padding", "5px 5px")]),
    dict(selector="tr", props=[("text-align", "center")]),
    dict(selector="caption", props=[("caption-side", "bottom")])
]

# creating some dummy data
index = pd.MultiIndex(levels=[['bar', 'baz', 'foo', 'qux'], ['one', 'two']],
                      labels=[[0, 0, 1, 1, 2, 2, 3, 3], [0, 1, 0, 1, 0, 1, 0, 1]],
                      names=['first', …
Run Code Online (Sandbox Code Playgroud)

css python pandas jupyter-notebook

8
推荐指数
2
解决办法
2633
查看次数

Sklearn Logistic回归,绘制概率曲线图

我正在尝试创建类似于ISLR的示例的逻辑回归,但改用python

data=pd.read_csv("data/Default.csv")

#first we'll have to convert the strings "No" and "Yes" to numeric values
data.loc[data["default"]=="No", "default"]=0
data.loc[data["default"]=="Yes", "default"]=1
X = data["balance"].values.reshape(-1,1)
Y = data["default"].values.reshape(-1,1)

LogR = LogisticRegression()
LogR.fit(X,np.ravel(Y.astype(int)))

#matplotlib scatter funcion w/ logistic regression
plt.scatter(X,Y)
plt.xlabel("Credit Balance")
plt.ylabel("Probability of Default")
Run Code Online (Sandbox Code Playgroud)

但是当我想要右边的图形时,我一直在左边得到图形:

在此处输入图片说明

编辑:plt.scatter(x,LogR.predict(x))是我的第二个,也是错误的猜测。

python scatter-plot pandas scikit-learn

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

带有 Inplace 的 Asyncio Pandas

我刚刚阅读了这个介绍,但是在实现其中一个示例时遇到了麻烦(注释代码是第二个示例):

import asyncio
import pandas as pd
from openpyxl import load_workbook

async def loop_dfs(dfs):
    async def clean_df(df):
        df.drop(["column_1"], axis=1, inplace=True)
        ... a bunch of other inplace=True functions ...
        return "Done"

    # tasks = [clean_df(df) for (table, dfs) in dfs.items()]
    # await asyncio.gather(*tasks)

    tasks = [clean_df(df) for (table, df) in dfs.items()]
    completed, pending = await asyncio.wait(tasks)


def main():
    dfs = {
        sn: pd.read_excel("excel.xlsx", sheet_name=sn)
        for sn in load_workbook("excel.xlsx").sheetnames
    }

    # loop = asyncio.get_event_loop()
    # loop.run_until_complete(loop_dfs(dfs))

    loop = asyncio.get_event_loop()
    try: …
Run Code Online (Sandbox Code Playgroud)

python python-3.x pandas python-asyncio

4
推荐指数
1
解决办法
4692
查看次数

堆栈如何按照与创建时不同的顺序处理弹出值?

我无法想到如何有效地标题,这可能就是为什么我找不到一个好的搜索.在Rust编程书中理解堆与堆栈时,我读到:

"数据类型"部分中涵盖的类型都存储在堆栈中,并在其作用域结束时从堆栈中弹出.

我阅读了更深入的区别,但我仍然很好奇如何在可以定义变量并在以后使用数百行时使用堆栈.举个例子:

let x = 5;
let y = 6;
println!("x = {}", x); // cannot just pop x off here as y was pushed last?
Run Code Online (Sandbox Code Playgroud)

澄清一下,堆栈是否用于作用域,但是在每个作用域内部还必须有一个堆来知道运行时的位置?

这是否意味着堆栈也在堆上分配?或者编译器是否将这两者完全分开?

对不起,如果这变成了一般关于编译器和内存管理的问题.

fn main() {                  // if this is all a stack
    let one = 1;             // stack.push(one)
    let two = 2;             // stack.push(two) 

    let three = one + two;   // stack.push(stack.pop() + stack.pop())???
}
Run Code Online (Sandbox Code Playgroud)

这有意义吗?我来自Python,所以请耐心等待.

stack rust

2
推荐指数
1
解决办法
125
查看次数

将 PeriodIndex 转换为

我有一个用于pd.Period索引的数据框,但后来需要使用该数据来绘制散景中的 x_axis。

df = return_data_with_multiindex()
df.reset_index(inplace=True, drop=False)
type(df["calDate"][0]) # returns pandas._period.Period
Run Code Online (Sandbox Code Playgroud)

不幸的是,散景不支持期间,所以我一直在思考如何最好地转换它。

TypeError: Object of type 'Period' is not JSON serializable
Run Code Online (Sandbox Code Playgroud)

这个答案没有帮助,因为我仍然不断抛出类型错误:

AttributeError                            Traceback (most recent call last)
<ipython-input-287-8753a9594163> in <module>()
      1 #pd.to_datetime(df["calDate"], format='%Y-%m')
----> 2 df["calDate"].to_timestamp()
      3 df[["calDate","freq_hist_deseas","freq_futr","freq_tr12"]]
      4 #type(df["calDate"][0])

C:\ANACONDA36\lib\site-packages\pandas\core\series.py in to_timestamp(self, freq, how, copy)
   2709             new_values = new_values.copy()
   2710 
-> 2711         new_index = self.index.to_timestamp(freq=freq, how=how)
   2712         return self._constructor(new_values,
   2713                                  index=new_index).__finalize__(self)

AttributeError: 'RangeIndex' object has no attribute 'to_timestamp'
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

编辑:这是一个例子:

                  col1 col2 col3
i1 i2 …
Run Code Online (Sandbox Code Playgroud)

python pandas bokeh

0
推荐指数
1
解决办法
1054
查看次数