我在试图弄清楚Python中的浅层和深层复制时一直在搞乱,并注意到虽然复制的集合,列表或看似任何可变类型的身份都不相同:
In[2]: x1 = {1,2,3}
In[3]: x2 = x1.copy()
In[4]: x1 is x2
Out[4]: False
Run Code Online (Sandbox Code Playgroud)
对于不可变类型,情况并非如此 - 它看起来像是指向内存中相同地址的副本.
In[6]: f1 = frozenset({1,2,3})
In[7]: f2 = f1.copy()
In[8]: f1 is f2
Out[8]: True
Run Code Online (Sandbox Code Playgroud)
这种直觉对我来说很有意义 - 为什么你在内存中需要两个相同的不可变对象呢?但我以前从未见过它 - 这个过程有没有名字?这是为了速度目的吗?
此外,这种"非实际复制"是否有任何影响?我不相信有,但我想确定 - 我唯一想到的就是如果有人决定修改一个不可变类型中的可变类型,从我所知道的反正是一个坏主意.
In[11]: t1 = tuple((1, ['a', 'b']))
In[12]: t2 = tuple(t1) # I would expect an actual copy, but it is not
In[13]: t1[1].append('c')
In[14]: t2
Out[14]: (1, ['a', 'b', 'c'])
Run Code Online (Sandbox Code Playgroud) 我有一个 DataFrame表示Advertising.csvdf中找到的 CSV 数据。
>>> df = pd.read_csv('Advertising.csv', index_col=0)
>>> df.head(5)
TV Radio Newspaper Sales
1 230.1 37.8 69.2 22.1
2 44.5 39.3 45.1 10.4
3 17.2 45.9 69.3 9.3
4 151.5 41.3 58.5 18.5
5 180.8 10.8 58.4 12.9
Run Code Online (Sandbox Code Playgroud)
我想将 DataFrame 中的每一列与各自散点图中的 Sales 列进行绘制,即

我设法做到了
import matplotlib.pyplot as plt
f, ax_l = plt.subplots(1, 3, figsize=(14, 4))
for e, col_name in enumerate(df.loc[:, :'Newspaper'].columns):
ax_l[e].scatter(df[col_name], df.Sales, alpha=0.5, color='r')
ax_l[e].set_xlabel(col_name)
ax_l[e].set_ylabel('Sales')
Run Code Online (Sandbox Code Playgroud)
我的问题是,是否有一个构造df.plot可以使这项任务比像我一样进入 Matplotlib 和循环更容易?
动机
我知道在 …
我开始阅读Nunez-Iglesias 等人写的《Elegant SciPy》。al,当打开书中的第一个数据集(文件.txt)时,作者使用
filename = 'data/counts.txt'
with open(filename, 'rt') as f:
data_table = pd.read_csv(f, index_col=0) # Parse file with pandas
Run Code Online (Sandbox Code Playgroud)
但我认为这read_csv会关闭文件,因为它是在给定文件描述符的情况下打开的(请参阅Andy Hayden 的回答此处)。
那么这里的上下文管理器有什么目的吗,或者我们可以安全地编写
filename = 'data/counts.txt'
data_table = pd.read_csv(filename, index_col=0)
Run Code Online (Sandbox Code Playgroud) 我有一个对象有4个数组参数,所有参数都应该是相同的长度.
public Foo(
int a,
int b,
type1[] arr1,
type2[] arr2,
type3[] arr3,
type4[] arr4
){ /* ... */ }
Run Code Online (Sandbox Code Playgroud)
我想确保所有这些数组在构造函数中的长度相同,但我显然不能这样做
if (!(arr1.Length == arr2.Length == arr3.Length == arr4.Length))
Run Code Online (Sandbox Code Playgroud)
所以我去了
if (!(arr1.Length == arr2.Length && arr2.Length == arr3.Length &&
arr3.Length == arr4.Length))
Run Code Online (Sandbox Code Playgroud)
但是这看起来并不是特别吸引人,如果我删除其中一个数组或其他东西,就不会那么清楚.
我认为必须有一个很好的方法来使用LINQ在它们的集合上执行此操作,但我的数组显然不是可枚举的.然后我有了创意(也许可能很傻)并想通过我可以用长度初始化一个hashset并检查它的长度是否为1.是否有一种标准/更好的方法来检查多个数组长度是否相等或者我的&&方法是否尽可能好得到?
假设我有一些 DataFrame(在我的例子中大约有 10000 行,这只是一个最小的例子)
>>> import pandas as pd
>>> sample_df = pd.DataFrame(
{'col1': list(range(1, 10)), 'col2': list(range(10, 19))})
>>> sample_df
col1 col2
0 1 10
1 2 11
2 3 12
3 4 13
4 5 14
5 6 15
6 7 16
7 8 17
8 9 18
Run Code Online (Sandbox Code Playgroud)
出于我的目的,我需要计算DataFrame 中ln(col_i(n+1) / col_i(n))每个代表的系列,其中代表行号。
我该如何计算这个?col_in
我知道我可以使用非常简单的方式获得每列之间的差异
>>> sample_df.diff()
col1 col2
0 NaN NaN
1 1 1
2 1 1
3 1 …Run Code Online (Sandbox Code Playgroud) 假设我有一个散点图,上面有某种线(最小二乘回归线、knn 回归线等),就像这样。
我想将绘图的上部区域涂成红色,将绘图的下部区域涂成蓝色,以表明我的线作为点的分类器的表现如何。与我的具有此效果的模拟示例类似,来自Elements of Statistical Learning ( Hastie 等人) (第 2 章,第 13 页) 中的此图。
如何使用 Matplotlib 实现这种效果?
我知道如何使用axhspan和将绘图的矩形区域设置为不同的颜色axvspan(请参阅此答案),但一直在努力根据线条上方和下方的区域设置不同的绘图颜色。
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('seaborn-notebook')
np.random.seed(17)
grp1_x = np.random.normal(1, 1, 100)
grp1_y = np.random.normal(3, 1, 100)
grp2_x = np.random.normal(1.2, 1, 100)
grp2_y = np.random.normal(1.2, 1, 100)
########################################
## least squares plot
plt.scatter(grp1_x, grp1_y,
lw = 1,
facecolors = 'none',
edgecolors = 'firebrick')
plt.scatter(grp2_x, grp2_y,
lw = …Run Code Online (Sandbox Code Playgroud) 假设我有一个DataFrame
df = pd.DataFrame(dict(vals=np.random.randint(0, 10, 10)),
index=pd.date_range('20170401', '20170410'))
>>> df
vals
2017-04-01 9
2017-04-02 8
2017-04-03 4
2017-04-04 5
2017-04-05 9
2017-04-06 9
2017-04-07 5
2017-04-08 3
2017-04-09 3
2017-04-10 1
Run Code Online (Sandbox Code Playgroud)
例如,我所知道的特定日期在我的索引中,但不知道其位置
cur_dt = df.index[np.random.randint(0, df.index.size)]
>>> cur_dt
Timestamp('2017-04-05 00:00:00', freq='D')
Run Code Online (Sandbox Code Playgroud)
鉴于cur_dt,我想确定索引中的上一个和下一个值是什么.应该cur_dt是我的索引中的第一个(最后一个)值,那么前一个(下一个)元素应该是cur_dt它自己.
回顾一下,我的问题是,在给定当前值的情况下,找到索引中的上一个和下一个值(或者如果它是一个端点的当前值本身)的最简单方法是什么?
我目前的做法似乎相当迂回,这是我提出要求的动机.
cur_iloc = df.index.get_loc(cur_dt)
prev = cur_dt if cur_iloc == 0 else df.index[cur_iloc-1]
next = cur_dt if cur_iloc == df.index.size-1 else df.index[cur_iloc+1]
>>> prev
Timestamp('2017-04-04 00:00:00', freq='D')
>>> …Run Code Online (Sandbox Code Playgroud) 我是 range-v3 库的完整初学者。假设我想std::array在某个时间间隔内用随机数填充 a 。
使用迭代器,我会做类似这个答案的事情,将迭代器std::array作为参数传递给我的问题。
template< class Iter >
void fill_with_random_int_values( Iter start, Iter end, int min, int max)
{
static std::random_device rd; // you only need to initialize it once
static std::mt19937 mte(rd()); // this is a relative big object to create
std::uniform_int_distribution<int> dist(min, max);
std::generate(start, end, [&] () { return dist(mte); });
}
Run Code Online (Sandbox Code Playgroud)
对于 range 库,我想使用ranges::view::generate_n, 和一个一元函数,该函数生成一个随机数以及数组的大小。
auto random_num() -> int {
static std::mt19937 engine{std::random_device{}()};
static std::uniform_int_distribution<int> dist(1, 10); …Run Code Online (Sandbox Code Playgroud) 在使用cookiecutter设置并使用xsimd启用SIMD内部函数之后,我尝试了xtensor-python,并开始编写一个非常简单的sum函数。
inline double sum_pytensor(xt::pytensor<double, 1> &m)
{
return xt::sum(m)();
}
inline double sum_pyarray(xt::pyarray<double> &m)
{
return xt::sum(m)();
}
Run Code Online (Sandbox Code Playgroud)
用于setup.py构建我的Python模块,然后与比较,测试了从np.random.randn不同大小构造的NumPy数组上的求和函数np.sum。
import timeit
def time_each(func_names, sizes):
setup = f'''
import numpy; import xtensor_basics
arr = numpy.random.randn({sizes})
'''
tim = lambda func: min(timeit.Timer(f'{func}(arr)',
setup=setup).repeat(7, 100))
return [tim(func) for func in func_names]
from functools import partial
sizes = [10 ** i for i in range(9)]
funcs = ['numpy.sum',
'xtensor_basics.sum_pyarray',
'xtensor_basics.sum_pytensor']
sum_timer = …Run Code Online (Sandbox Code Playgroud) 我有一个具有以下结构的示例。
??? CMakeLists.txt
??? ext
? ??? pybind11
??? main.cpp
Run Code Online (Sandbox Code Playgroud)
CMakeLists.txt
cmake_minimum_required(VERSION 3.5)
project(notworking)
add_subdirectory(ext/pybind11)
add_executable(notworking
main.cpp)
target_link_libraries(notworking PRIVATE python3.6m)
target_link_libraries(notworking PRIVATE pybind11)
Run Code Online (Sandbox Code Playgroud)
主程序
#include <pybind11/pybind11.h>
namespace py = pybind11;
int main() { py::object decimal = py::module::import("decimal"); }
Run Code Online (Sandbox Code Playgroud)
现在在运行时
?? ./notworking
[1] 14879 segmentation fault (core dumped) ./notworking
Run Code Online (Sandbox Code Playgroud)
我错过了什么才能让这个模块在这里正确加载?我已经搜索了文档,特别是构建系统部分,但发现是空的。
在 C++ 的 pybind11 中使用其他包装器时,对我来说似乎也是这种情况。
python ×8
pandas ×4
c++ ×3
dataframe ×3
matplotlib ×2
numpy ×2
plot ×2
arrays ×1
c# ×1
c++20 ×1
file ×1
performance ×1
pybind11 ×1
python-3.x ×1
range-v3 ×1
regression ×1
series ×1
xtensor ×1