我认为这应该很容易,但我有点像墙了.我有一个数据集从Stata .dta文件导入到pandas数据框中.其中一些列包含日期数据.数据框包含100,000多行,但给出了一个示例:
cat event_date total
0 G2 2006-03-08 16
1 G2 NaT NaN
2 G2 NaT NaN
3 G3 2006-03-10 16
4 G3 2006-08-04 12
5 G3 2006-12-28 13
6 G3 2007-05-25 10
7 G4 2006-03-10 13
8 G4 2006-08-06 19
9 G4 2006-12-30 16
Run Code Online (Sandbox Code Playgroud)
数据存储为datetime64格式:
>>> mydata[['cat','event_date','total']].dtypes
cat object
event_date datetime64[ns]
total float64
dtype: object
Run Code Online (Sandbox Code Playgroud)
我想要做的就是创建一个新列,它在event_date和开始日期之间(例如2006-01-01)给出了天数(而不是'us'或'ns'!!!)的差异.我尝试过以下方法:
>>> mydata['new'] = mydata['event_date'] - np.datetime64('2006-01-01')
Run Code Online (Sandbox Code Playgroud)
......但我收到的消息是:
TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely …Run Code Online (Sandbox Code Playgroud) 我有一个pandas数据帧,具有以下结构:
import numpy as np
import pandas as pd
myData = pd.DataFrame({'x': [1.2,2.4,5.3,2.3,4.1], 'y': [6.7,7.5,8.1,5.3,8.3], 'condition':[1,1,np.nan,np.nan,1],'calculation': [np.nan]*5})
print myData
calculation condition x y
0 NaN 1 1.2 6.7
1 NaN 1 2.4 7.5
2 NaN NaN 5.3 8.1
3 NaN NaN 2.3 5.3
4 NaN 1 4.1 8.3
Run Code Online (Sandbox Code Playgroud)
我想根据'x'和'y'(例如x/y)中的值在'calculation'列中输入一个值,但仅限于'condition'列包含NaN的那些单元格中(np.isnan(myData [ 'condition']).最终的数据框应如下所示:
calculation condition x y
0 NaN 1 1.2 6.7
1 NaN 1 2.4 7.5
2 0.654 NaN 5.3 8.1
3 0.434 NaN 2.3 5.3
4 NaN 1 4.1 8.3 …Run Code Online (Sandbox Code Playgroud) 我在使用Python 3.4运行El Capitan 10.11.6的Mac上安装了Python映射工具Cartopy.我可以使用Cartopy成功绘制一些地图,但在某些情况下,Python内核会死于Segmentation Fault 11.
我想要一个可以在需要时从我的计算机上轻松删除的设置.因此,我使用fink安装了Python 3.4和必要的依赖项:
$ fink install python34
$ fink install gdal2
$ fink install gdal2-dev
$ fink install proj
$ fink install libproj9
Run Code Online (Sandbox Code Playgroud)
然后我使用pyvenv(但也试过virtualenv和venv)创建了一个虚拟环境并激活它.
在激活的虚拟环境中,我使用pip来安装:
$ pip install cython # Successfully installed cython-0.25.2
$ pip install numpy # Successfully installed numpy-1.12.1
$ pip install shapely # Successfully installed shapely-1.5.17.post1
$ pip install pyshp # Successfully installed pyshp-1.2.10
$ pip install pandas # Successfully installed pandas-0.19.2 python-dateutil-2.6.0 pytz-2017.2 six-1.10.0
$ pip install matplotlib # Successfully installed …Run Code Online (Sandbox Code Playgroud) 我正在使用numpy 0.10.1和pandas 0.17.0的Python 3.4.1。我有一个大型的数据框,其中列出了单个动物的种类和性别。这是一个真实的数据集,不可避免地存在NaN表示的缺失值。数据的简化版本可以生成为:
import numpy as np
import pandas as pd
tempDF = pd.DataFrame({ 'id': [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],
'species': ["dog","dog",np.nan,"dog","dog","cat","cat","cat","dog","cat","cat","dog","dog","dog","dog",np.nan,"cat","cat","dog","dog"],
'gender': ["male","female","female","male","male","female","female",np.nan,"male","male","female","male","female","female","male","female","male","female",np.nan,"male"]})
Run Code Online (Sandbox Code Playgroud)
打印数据框将得到:
gender id species
0 male 1 dog
1 female 2 dog
2 female 3 NaN
3 male 4 dog
4 male 5 dog
5 female 6 cat
6 female 7 cat
7 NaN 8 cat
8 male 9 dog
9 male 10 cat
10 female 11 cat
11 male 12 dog
12 female 13 dog
13 female 14 …Run Code Online (Sandbox Code Playgroud) 出于所有目的和目的,我是Python用户,每天使用Pandas库。正则表达式中的命名捕获组非常有用。因此,例如,提取特定单词或短语的出现并在数据帧的新列中生成结果的串联字符串是相对琐碎的。下面是如何实现此目的的示例:
import numpy as np
import pandas as pd
import re
myDF = pd.DataFrame(['Here is some text',
'We all love TEXT',
'Where is the TXT or txt textfile',
'Words and words',
'Just a few works',
'See the text',
'both words and text'],columns=['origText'])
print("Original dataframe\n------------------")
print(myDF)
# Define regex to find occurrences of 'text' or 'word' as separate named groups
myRegex = """(?P<textOcc>t[e]?xt)|(?P<wordOcc>word)"""
myCompiledRegex = re.compile(myRegex,flags=re.I|re.X)
# Extract all occurrences of 'text' or 'word'
myMatchesDF = myDF['origText'].str.extractall(myCompiledRegex)
print("\nDataframe of matches (with …Run Code Online (Sandbox Code Playgroud) 我有一个从 SQL 数据库导入的大型 Pandas 数据框。整个过程需要几个小时。当我处理数据时,数据帧不可避免地会发生变化,我经常想返回“已知的良好数据集”并重新运行各种函数。我不想从数据库导入数据,而是想将分析过程中各个点的数据保存为 CSV 文件,然后可以根据需要使用该文件恢复数据;CSV 是首选格式,因为出于某种原因,我在腌制数据帧方面运气不佳。只需使用 pd.read_csv() 导入 CSV 数据即可更改列的数据类型。因此,我想创建一个 dtypes 字典,可用于在将 CSV 导入回数据帧时恢复数据类型。
例如,一个简单的数据框可以定义如下:
df = pd.DataFrame({'A':[1,2,3,4,5],'B':['a','b','c','d','e'],'C':[1.2,3.4,5.6,7.8,9.0]},index=[0,2,4,6,8])
Run Code Online (Sandbox Code Playgroud)
看起来像:
A B C
0 1 a 1.2
2 2 b 3.4
4 3 c 5.6
6 4 d 7.8
8 5 e 9.0
Run Code Online (Sandbox Code Playgroud)
可以使用以下命令创建数据类型字典:
dtypesDict = df.dtypes.to_dict()
Run Code Online (Sandbox Code Playgroud)
其产生:
{'B': dtype('O'), 'C': dtype('float64'), 'A': dtype('int64')}
Run Code Online (Sandbox Code Playgroud)
如果我尝试使用此输出以硬代码定义字典,以便可以使用它来设置使用导入的列的数据类型pd.read_csv(),则会失败,如下所示:
dtypesDict = {'B': dtype('O'), 'C': dtype('float64'), 'A': dtype('int64')}
NameError: name 'dtype' is not defined
Run Code Online (Sandbox Code Playgroud)
然而,将字典定义为:
dtypesDict = {'B': 'O', 'C': 'float64', 'A': …Run Code Online (Sandbox Code Playgroud) 我刚刚开始使用Latex生成大量数学文档。我想包含一个概率树,并找到了Tikz库。我的树的第一部分代码如下所示:
%To create probability trees, use tikz package
\usepackage{tikz}
\usetikzlibrary{trees}
% Insert a probability tree showing first level only
% -------------------------------------------------------------
% Set the overall layout of the tree
\tikzstyle{level 1}=[level distance=3.5cm, sibling distance=4.0cm]
\tikzstyle{level 2}=[level distance=3.5cm, sibling distance=2cm]
% Define styles for bags and leafs
\tikzstyle{bag} = [text centered]
% Draw probability tree
\begin{tikzpicture}[grow=right, sloped]
\node[bag] {}
child {
node[bag] {Not diseased $\left( D^- \right)$}
edge from parent
node[below] {$0.90$}
}
child {
node[bag] {Diseased $\left( D^+ \right)$}
edge …Run Code Online (Sandbox Code Playgroud) 我是使用 statsmodels 进行统计分析的新手。我大多数时候都会得到预期的答案,但有些事情我不太明白 statsmodels 在以字符串形式输入时定义逻辑回归的 endog(依赖)变量的方式。
可以定义如下所示的示例 Pandas 数据框来说明该问题。yN、yA 和 yA2 列代表定义 endog 变量的不同方式: yN 是编码为 0、1 的二进制变量;yA 是一个二进制变量,编码为“y”、“n”;yA2 是编码为“x”、“y”和“w”的变量:
import pandas as pd
df = pd.DataFrame({'yN':[0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1],
'yA':['y','y','y','y','y','y','y','n','n','n','n','n','n','n','n','n','n','n','n','n',],
'yA2':['y','y','y','w','y','w','y','n','n','n','n','n','n','n','n','n','n','n','n','n',],
'xA':['a','a','b','b','b','c','c','c','c','c','a','a','a','a','b','b','b','b','c','c']})
Run Code Online (Sandbox Code Playgroud)
数据框看起来像:
xA yA yA2 yN
0 a y y 0
1 a y y 0
2 b y y 0
3 b y w 0
4 b y y 0
5 c y w 0
6 c y y 0
7 c n n 1
8 c n n 1 …Run Code Online (Sandbox Code Playgroud) 我最近开始使用 GeoPandas 来制作地图,发现它非常有用。我已经使用 Pandas 一段时间了,我发现迁移到 GeoPandas 相对轻松。但是,在使用 .dissolve() 函数对点进行分组后,我在地图上绘制点时遇到问题。
\n\n基本上,我从国家统计局邮政编码目录 (ONSPD) 下载了一系列英国邮政编码数据以及相关的经度和纬度值。经度和纬度值基于 CRS WGS84。我可以转换为 CRS OSGB36 并毫无问题地在地图上绘制所有点。但是,如果我使用 .dissolve() 方法根据其他变量(例如“group1”和“groups”)对点进行分组,我将无法再绘制这些点。
\n\n这是我迄今为止将所有点绘制在一起的代码:
\n\nimport pandas as pd\nimport geopandas as gif\nimport matplotlib.pyplot as plot\nimport shapely\n\n# Define a Pandas dataframe containing postcodes and \npostcodeDF = pd.DataFrame({\'pcd\': [\'RM175AG\', \'NP181PH\', \'LS8 1EN\', \'HG1 1XQ\', \'G11 6YB\', \'TN218AB\', \'GU138AL\', \'CV344BD\', \'YO126PH\', \'SO172WT\', \'PR2 8HN\', \'TF1 2HD\', \'M31 4FR\', \'CH460UB\', \'EX111LN\', \'TS214DX\', \'BN4 2LS\', \'FY8 1XL\', \'KA256BP\', \'DA1 1QR\'],\n \'ctry\': [\'E92000001\', \'W92000004\', \'E92000001\', \'E92000001\', \'S92000003\', \'E92000001\', …Run Code Online (Sandbox Code Playgroud) 我有一个大熊猫数据框,可以在结构上表示为:
id date status
0 12 2015-05-01 0
1 12 2015-05-22 1
2 12 2015-05-14 1
3 12 2015-05-06 0
4 45 2015-05-03 1
5 45 2015-05-12 1
6 45 2015-05-02 0
7 51 2015-05-05 1
8 51 2015-05-01 0
9 51 2015-05-23 1
10 51 2015-05-17 1
11 51 2015-05-03 0
12 51 2015-05-05 0
13 76 2015-05-04 1
14 76 2015-05-22 1
15 76 2015-05-08 0
Run Code Online (Sandbox Code Playgroud)
并且可以使用以下命令在 Python 3.4 中创建:
tempDF = pd.DataFrame({ 'id': [12,12,12,12,45,45,45,51,51,51,51,51,51,76,76,76],
'date': ['2015-05-01','2015-05-22','2015-05-14','2015-05-06','2015-05-03','2015-05-12','2015-05-02','2015-05-05','2015-05-01','2015-05-23','2015-05-17','2015-05-03','2015-05-05','2015-05-04','2015-05-22','2015-05-08'],
'status': …Run Code Online (Sandbox Code Playgroud) 我有一个包含分组变量的 Pandas 数据框。可以使用以下方法生成一个示例:
df = pd.DataFrame({'grp':['a','a','b','b','b','c','d','d','d','d'],
'data':[4,5,3,6,7,8,9,8,7,3]})
Run Code Online (Sandbox Code Playgroud)
...看起来像:
grp data
0 a 4
1 a 5
2 b 3
3 b 6
4 b 7
5 c 8
6 d 9
7 d 8
8 d 7
9 d 3
Run Code Online (Sandbox Code Playgroud)
我可以使用以下方法检索每组的最后两行:
dfgrp = df.groupby('grp').tail(2)
Run Code Online (Sandbox Code Playgroud)
但是,我想生成一个掩码来标识最后两行(如果仅存在 1 行,则为 1 行),理想情况下会生成如下所示的输出:
0 True
1 True
2 False
3 True
4 True
5 True
6 False
7 False
8 True
9 True
Run Code Online (Sandbox Code Playgroud)
我认为这相对简单,但我一直无法找到解决方案。如有建议,我们将不胜感激。
python ×10
pandas ×7
dataframe ×4
matplotlib ×2
python-3.x ×2
cartopy ×1
crosstab ×1
csv ×1
datetime64 ×1
fink ×1
geopandas ×1
gis ×1
latex ×1
nan ×1
numpy ×1
r ×1
regex ×1
regex-group ×1
sorting ×1
statsmodels ×1
tikz ×1
types ×1