我一直在寻找一种优雅的方式来改变一个指定的列名DataFrame.
播放数据......
import pandas as pd
d = {
'one': [1, 2, 3, 4, 5],
'two': [9, 8, 7, 6, 5],
'three': ['a', 'b', 'c', 'd', 'e']
}
df = pd.DataFrame(d)
Run Code Online (Sandbox Code Playgroud)
到目前为止我找到的最优雅的解决方案......
names = df.columns.tolist()
names[names.index('two')] = 'new_name'
df.columns = names
Run Code Online (Sandbox Code Playgroud)
我希望有一个简单的单行...这次尝试失败了......
df.columns[df.columns.tolist().index('one')] = 'another_name'
Run Code Online (Sandbox Code Playgroud)
感激地收到任何提示.
对于Series对象(让我们称之为s),pandas提供了三种类型的寻址.
s.iloc [] - 用于整数位置寻址;
s.loc [] - 用于索引标签寻址; 和
s.ix [] - 用于整数位置和标签寻址的混合.
pandas对象还直接执行ix寻址.
# play data ...
import string
idx = [i for i in string.uppercase] # A, B, C .. Z
t = pd.Series(range(26), index=idx) # 0, 1, 2 .. 25
# examples ...
t[0] # --> 0
t['A'] # --> 0
t[['A','M']] # --> [0, 12]
t['A':'D'] # --> [0, 1, 2, 3]
t.iloc[25] # --> 25
t.loc['Z'] # --> 25
t.loc[['A','Z']] # --> [0, 25] …Run Code Online (Sandbox Code Playgroud) 如果你看这里的图表!你可以看到传说上下有很多空白区域.我希望减少空间.
示例代码:
library(ggplot2)
library(gridExtra)
library(reshape)
library(plyr)
library(scales)
theme_set(theme_bw())
rows <- 1:nrow(faithful)
data <- cbind(faithful, rows)
molten <- melt(data, id.vars='rows', measure.vars=c('eruptions', 'waiting'))
p <- ggplot() +
geom_line(data=molten,
mapping=aes(x=rows, y=value, group=variable, colour=variable), size=0.8) +
scale_colour_manual(values=c('red','blue')) +
opts(title='Title') +
xlab(NULL) + ylab('Meaningless Numbers') +
opts(
legend.position='bottom',
legend.direction='horizontal',
legend.title=theme_blank(),
legend.key=theme_blank(),
legend.text=theme_text(size=9),
legend.margin = unit(0, "line"),
legend.key.height=unit(0.6,"line"),
legend.background = theme_rect(colour='white', size=0)
)
ggsave(p, width=8, height=4, filename='crap.png', dpi=125)
Run Code Online (Sandbox Code Playgroud) 我可以通过做这样的事情在ggplot2中以不同的颜色绘制每个系列...
colours <- c('red', 'blue')
p <- ggplot(data=m, mapping=aes_string(x='Date', y='value'))
p <- p + geom_line(mapping=aes_string(group='variable', colour='variable'), size=0.8)
p <- p + scale_colour_manual(values=colours)
Run Code Online (Sandbox Code Playgroud)
我能为每个系列设置不同的线宽吗?(即我想使用粗红线绘制趋势,使用细蓝线绘制经季节性调整的系列.)
我使用 let 块在 Julia 中拼凑了一个闭包。
counter = let
local counter = 0 # local variable
f() = counter += 1 # returned function
end
counter(); counter(); counter()
print(counter()) # 4
Run Code Online (Sandbox Code Playgroud)
这是朱莉娅的犹太洁食吗?
我有一个很大的 CSV 文件——将近 2800 万行和 57 列——8.21GB——数据是不同类型的——整数、字符串、浮点数——但没有什么不寻常的。
当我在 Python/Pandas 中加载它时,使用以下代码需要 161 秒。
df = pd.read_csv("file.csv", header=0, low_memory=False)
Run Code Online (Sandbox Code Playgroud)
在 Julia 中,它需要更长的时间 - 一个多小时。更新:我不知道为什么,但是当我今天早上运行代码(检查两次)时,它花了大约 702 和 681 秒。这比一个小时好多了,但它仍然比 Python 慢得多。
我的 Julia 代码也很简单:
df = CSV.File("file.csv") |> DataFrame
Run Code Online (Sandbox Code Playgroud)
难道我做错了什么?有什么我可以做的来加快速度吗?或者这只是你和朱莉娅一起玩的代价?
我没有锁定其中一个字段时可以复制R5引用类,但如果其中一个字段被锁定则不会复制.示例代码如下(锁定调用已注释掉).我的问题:为什么我不能使用copy()方法复制带有锁定字段的实例?
example <- setRefClass('example',
fields = list(
count = 'numeric',
data = 'data.frame',
d.accessor = function(x) {
if ( !missing(x) )
data <<- x
else
.self$data
}
),
methods = list(
initialize = function( data ) {
if (!missing( data ))
d.accessor <<- data
count <<- 0
},
finalize = function()
print('Bye Bye'),
accumulate = function(x)
count <<- count + x
)
)
#example$lock('data') # write-1, read-many
instance <- example$new() # instantiation
df <- data.frame(x=1, y=2)# example df
instance$d.accessor <- …Run Code Online (Sandbox Code Playgroud) 是否有一种快速而肮脏的方法来测试实例是否来自引用类?
标准的R对象测试产生以下结果 - 但似乎没有任何东西专门标记引用类.
classy <- setRefClass('classy',
fields = list(
count = 'numeric'
),
methods = list(
initialize = function( data=NULL ) {
.self$data <<- data
}
)
)
instance <- classy$new() # instantiation
isS4(instance) # TRUE
mode(instance) # "S4"
typeof(instance) # "S4"
class(instance) # [1] "classy" attr(,"package") [1] ".GlobalEnv"
dput(instance) # new("classy", .xData = <environment>)
str(instance) #
# Reference class 'classy' [package ".GlobalEnv"] with 1 fields
# $ count: num(0)
# and 13 methods, of which 1 are possibly …Run Code Online (Sandbox Code Playgroud) I am doing a multiple regression in Stan.
I want a trace plot of the beta vector parameter for the regressors/design matrix.
When I do the following:
fit = model.sampling(data=data, iter=2000, chains=4)
fig = fit.plot('beta')
Run Code Online (Sandbox Code Playgroud)
I get a pretty horrid image:
I was after something a little more user friendly. I have managed to hack the following which is closer to what I am after.
My hack plugs into the back of pystan as follows.
r = fit.extract() # r …Run Code Online (Sandbox Code Playgroud) 我试图使用ggplot绘制概率密度图.我的问题是曲线下面积不等于1.建议表示赞赏.
示例图表...生成此图表的代码如下:Y轴看起来像是小尺寸箱柜的计数,而不是落入该箱柜的概率.这里的示例代码是我在编写此图表时提供的资源之一.

示例代码......其中大部分是数据......代码的关键位在底部......
library(ggplot2)
library(reshape)
library(plyr)
library(scales)
Date <- as.Date(
c("1976-01-16", "1976-02-15", "1976-03-16", "1976-04-15", "1976-05-16",
"1976-06-15", "1976-07-16", "1976-08-16", "1976-09-15", "1976-10-16",
"1976-11-15", "1976-12-16", "1977-01-16", "1977-02-14", "1977-03-16",
"1977-04-15", "1977-05-16", "1977-06-15", "1977-07-16", "1977-08-16",
"1977-09-15", "1977-10-16", "1977-11-15", "1977-12-16", "1978-01-16",
"1978-02-14", "1978-03-16", "1978-04-15", "1978-05-16", "1978-06-15",
"1978-07-16", "1978-08-16", "1978-09-15", "1978-10-16", "1978-11-15",
"1978-12-16", "1979-01-16", "1979-02-14", "1979-03-16", "1979-04-15",
"1979-05-16", "1979-06-15", "1979-07-16", "1979-08-16", "1979-09-15",
"1979-10-16", "1979-11-15", "1979-12-16", "1980-01-16", "1980-02-15",
"1980-03-16", "1980-04-15", "1980-05-16", "1980-06-15", "1980-07-16",
"1980-08-16", "1980-09-15", "1980-10-16", "1980-11-15", "1980-12-16",
"1981-01-16", "1981-02-14", "1981-03-16", "1981-04-15", "1981-05-16",
"1981-06-15", "1981-07-16", "1981-08-16", …Run Code Online (Sandbox Code Playgroud) 此链接具有R代码以复制ggplot的颜色:使用qplot绘制函数系列而不复制数据
我已经去过复制python中的代码 - 但结果不对...
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import math
import colorsys
# function to return a list of hex colour strings
def colorMaker(n=12, start=15.0/360.0, saturation=1.0, valight=0.65) :
listOfColours = []
for i in range(n) :
hue = math.modf(float(i)/float(n) + start)[0]
#(r,g,b) = colorsys.hsv_to_rgb(hue, saturation, valight)
(r,g,b) = colorsys.hls_to_rgb(hue, valight, saturation)
listOfColours.append( '#%02x%02x%02x' % (int(r*255), int(g*255), int(b*255)) )
return listOfColours
# made up data
x = np.array(range(20))
d = {}
d['y1'] …Run Code Online (Sandbox Code Playgroud)