我正在使用Seaborn的lmplot绘制线性回归,将我的数据集分成两组,并带有分类变量.
对于x和y,我想在两个图上手动设置下限,但是将上限保留在Seaborn默认值上.这是一个简单的例子:
import pandas as pd
import seaborn as sns
import random
n = 200
random.seed(2014)
base_x = [random.random() for i in range(n)]
base_y = [2*i for i in base_x]
errors = [random.uniform(0,1) for i in range(n)]
y = [i+j for i,j in zip(base_y,errors)]
df = pd.DataFrame({'X': base_x,
'Y': y,
'Z': ['A','B']*(n/2)})
mask_for_b = df.Z == 'B'
df.loc[mask_for_b,['X','Y']] = df.loc[mask_for_b,] *2
sns.lmplot('X','Y',df,col='Z',sharex=False,sharey=False)
Run Code Online (Sandbox Code Playgroud)
这输出如下:
但在这个例子中,我希望xlim和ylim为(0,*).我尝试使用sns.plt.ylim和sns.plt.xlim但这些只影响右手图.例:
sns.plt.ylim(0,)
sns.plt.xlim(0,)
Run Code Online (Sandbox Code Playgroud)
如何访问FacetGrid中每个绘图的xlim和ylim?
我正在开发一个"预测模型即服务"的应用程序,结构如下:
我正在尝试使用patsy,但遇到以下问题:当单个预测进入时,如何将其转换为正确的形状,使其看起来像一行训练数据?
patsy文档提供了一个示例,当训练数据中的DesignInfo在内存中可用时:http://patsy.readthedocs.io/en/latest/library-developers.html#predictions
# offline model training
import patsy
data = {'animal': ['cat', 'cat', 'dog', 'raccoon'], 'cuteness': [3, 6, 10, 4]}
eq_string = "cuteness ~ animal"
dmats = patsy.dmatrices(eq_string,data)
design_info = dmats[1].design_info
train_model(dmats)
# online predictions
input_data = {'animal': ['raccoon']}
# if the DesignInfo were available, I could do this:
new_dmat = build_design_matrices([design_info], input_data)
make_prediction(new_dmat, trained_model)
Run Code Online (Sandbox Code Playgroud)
然后是输出:
[DesignMatrix with shape (1, 3)
Intercept animal[T.dog] animal[T.raccoon]
1 0 1
Terms:
'Intercept' (column 0)
'animal' (columns …
Run Code Online (Sandbox Code Playgroud) 我刚升级到IPython 2.0.0并且tab-complete的行为似乎已经变得更糟.(使用pyreadline 2.0,根据这个问题可能很重要).
以前,如果我之后点击TAB function_name(
,IPython会显示该函数的文档字符串.
现在,我只看到一个下拉列表,其中包含命名空间中的所有内容,包括:
旧的行为非常有用 - 如何恢复它(没有恢复到早期的IPython版本)?
我是康达的新手,看到一些奇怪的东西,但我实际上并不知道这是不是问题.
我目前处于根环境中.在某些时候我试图在另一个环境中安装pip,但不小心跑了pip install requests
.这似乎已经在我的root环境中安装了它:
$ conda list | grep requests
requests 2.12.4 py36_0
requests 2.13.0 <pip>
Run Code Online (Sandbox Code Playgroud)
它看起来像pip版本是我运行python时得到的:
$ python
Python 3.6.0 |Continuum Analytics, Inc.| (default, Dec 23 2016, 12:22:00)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests; requests.__version__
'2.13.0'
Run Code Online (Sandbox Code Playgroud)
我的猜测是,周围有两个版本的同一个包会导致后来的麻烦.然后我的假设是我最好保留非点子版本,所以我尝试了这个:
$ pip uninstall requests
[asks for confirmation, say yes]
$ conda list
[traceback, which I can post if helpful. Summary is:]
ModuleNotFoundError: No module named 'requests' …
Run Code Online (Sandbox Code Playgroud) 我有兴趣在python中运行一个有序的logit回归(使用pandas,numpy,sklearn或者那个生态系统).但我找不到任何方法来做到这一点.我的谷歌技能缺乏吗?或者这不是在标准包中实现的东西?
我想取一列日期时间对象并返回一列整数,这些整数是“从那个日期时间到今天的天数”。我可以用一种丑陋的方式来做,寻找一种更漂亮(更快)的方式。
所以假设我有一个带有日期时间列的数据框,如下所示:
11 2014-03-04 17:16:26+00:00
12 2014-03-10 01:35:56+00:00
13 2014-03-15 02:35:51+00:00
14 2014-03-20 05:55:47+00:00
15 2014-03-26 04:56:33+00:00
Name: datetime, dtype: object
Run Code Online (Sandbox Code Playgroud)
每个元素看起来像:
datetime.datetime(2014, 3, 4, 17, 16, 26, tzinfo=<UTC>)
Run Code Online (Sandbox Code Playgroud)
假设我想计算每次观察发生的天数,并将其作为一个简单的整数返回。我知道我只能使用apply
两次,但有没有一种矢量化/更清洁的方法来做到这一点?
today = datetime.datetime.today().date()
df_dates = df['datetime'].apply(lambda x: x.date())
days_ago = today - df_dates
Run Code Online (Sandbox Code Playgroud)
这给出了一个 timedelta64[ns] 系列。
11 56 days, 00:00:00
12 50 days, 00:00:00
13 45 days, 00:00:00
14 40 days, 00:00:00
15 34 days, 00:00:00
Name: datetime, dtype: timedelta64[ns]
Run Code Online (Sandbox Code Playgroud)
最后,如果我想要它作为一个整数:
days_ago_as_int = days_ago.apply(lambda x: x.item().days)
days_ago_as_int
11 …
Run Code Online (Sandbox Code Playgroud) 在Python中:
In [1]: True+True
Out[1]: 2
Run Code Online (Sandbox Code Playgroud)
因此,在进行以下设置之后:
import pandas as pd
ser1 = pd.Series([True,True,False,False])
ser2 = pd.Series([True,False,True,False])
Run Code Online (Sandbox Code Playgroud)
我想要的是找到ser1
and 的元素明智的总和,ser2
布尔值被视为整数,如Python示例所示。
但是,Pandas将加法视为元素式“或”运算符,并提供以下(不需要的)输出:
In [5]: ser1+ser2
*/lib/python2.7/site-packages/pandas/computation/expressions.py:184: UserWarning: evaluating in Python space because the '+' operator is not supported by numexpr for the bool dtype, use '|' instead
unsupported[op_str]))
Out[5]:
0 True
1 True
2 True
3 False
dtype: bool
Run Code Online (Sandbox Code Playgroud)
我知道我可以在任何一个系列上得到我想要的输出astype(int)
:
In [6]: ser1.astype(int) + ser2
Out[6]:
0 2
1 1
2 1
3 0 …
Run Code Online (Sandbox Code Playgroud) 似乎'5187621769'应该是一个非常容易的数字,供phonenumbers库解析.这是10位数字,带有美国区号.但是......没有运气.
建立:
import phonenumbers
number = '5187621769'
Run Code Online (Sandbox Code Playgroud)
方法1:
parsed = phonenumbers.parse(number)
Run Code Online (Sandbox Code Playgroud)
这会引发错误.
方法2:
parsed = phonenumbers.parse("+" + number)
Run Code Online (Sandbox Code Playgroud)
给出国家代码= 51,这不是美国.
我知道我能做到:
parsed = phonenumbers.parse(number,region="US")
Run Code Online (Sandbox Code Playgroud)
但我并不总是知道这个数字将是美国(这只是我发现我没有得到理想行为的一个案例).有没有我缺少的选项或格式技巧?谢谢!
获取以下数据框:
import pandas as pd
df = pd.DataFrame({'group_name': ['A','A','A','B','B','B'],
'timestamp': [4,6,1000,5,8,100],
'condition': [True,True,False,True,False,True]})
Run Code Online (Sandbox Code Playgroud)
我想添加两列:
condition
每组内列的滚动总和我知道我可以通过自定义申请来做到这一点,但我想知道是否有人有任何有趣的想法?(当有很多组时,这也很慢。)这是一种解决方案:
def range_within_group(input_df):
df_to_return = input_df.copy()
df_to_return = df_to_return.sort('timestamp')
df_to_return['order_within_group'] = range(len(df_to_return))
df_to_return['rolling_sum_of_condition'] = df_to_return.condition.cumsum()
return df_to_return
df.groupby('group_name').apply(range_within_group).reset_index(drop=True)
Run Code Online (Sandbox Code Playgroud) 观察这个奇怪的行为:
In [1]: import pandas as pd
In [2]: import datetime
In [3]: import pytz
In [4]: dates = [datetime.datetime(2015,1,i,tzinfo=pytz.timezone('US/Pacific')) for i in range(1,5)]
In [5]: df = pd.DataFrame({'A': ['a','b']*2,'B': dates})
In [6]: df
Out[6]:
A B
0 a 2015-01-01 00:00:00-08:00
1 b 2015-01-02 00:00:00-08:00
2 a 2015-01-03 00:00:00-08:00
3 b 2015-01-04 00:00:00-08:00
In [7]: grouped = df.groupby('A')
In [8]: grouped.nth(0) #B stays a datetime.datetime with timezone info
Out[8]:
B
A
a 2015-01-01 00:00:00-08:00
b 2015-01-02 00:00:00-08:00
In [9]: grouped.head(1) …
Run Code Online (Sandbox Code Playgroud) Can anyone provide an explanation of what it means to have a "slice" vs. a "copy" in pandas? I've been working with pandas for a while, and have internalized some rules of thumb about how to avoid the warnings.
But a colleague had some weird behavior today that I think is traceable to the same distinction, and it made me realize that I don't really understand what's going on under the hood and how it plays out in different situation. …