我已经在Pandas中读取了一个SQL查询,并且这些值以dtype'object'形式出现,尽管它们是字符串,日期和整数.我能够将日期'对象'转换为Pandas datetime dtype,但是在尝试转换字符串和整数时遇到错误.
这是一个例子:
>>> import pandas as pd
>>> df = pd.read_sql_query('select * from my_table', conn)
>>> df
id date purchase
1 abc1 2016-05-22 1
2 abc2 2016-05-29 0
3 abc3 2016-05-22 2
4 abc4 2016-05-22 0
>>> df.dtypes
id object
date object
purchase object
dtype: object
Run Code Online (Sandbox Code Playgroud)
将df['date']日期转换为日期时间:
>>> pd.to_datetime(df['date'])
1 2016-05-22
2 2016-05-29
3 2016-05-22
4 2016-05-22
Name: date, dtype: datetime64[ns]
Run Code Online (Sandbox Code Playgroud)
但是在尝试将其转换df['purchase']为整数时出现错误:
>>> df['purchase'].astype(int)
....
pandas/lib.pyx in pandas.lib.astype_intsafe (pandas/lib.c:16667)()
pandas/src/util.pxd in util.set_value_at (pandas/lib.c:67540)()
TypeError: …Run Code Online (Sandbox Code Playgroud) 我有一个数据集两个连续变量和一个因子变量(两个类).我想创建一个带有两个质心(每个类一个)的散点图,其中包含R中的误差条.质心应位于每个类的x和y的平均值.
我可以使用ggplot2轻松创建散点图,但我无法弄清楚如何添加质心.是否可以使用ggplot/qplot来做到这一点?
这是一些示例代码:
x <- c(1,2,3,4,5,2,3,5)
y <- c(10,11,14,5,7,9,8,5)
class <- c(1,1,1,0,0,1,0,0)
df <- data.frame(class, x, y)
qplot(x,y, data=df, color=as.factor(class))
Run Code Online (Sandbox Code Playgroud) 我正在尝试pandas.DataFrame直接写入Google云端硬盘,而无需先在本地写入文件.我找不到解决方案,也不确定它是否可行.我已经尝试了下面的代码,但我得到了一个AttributeError.
import pandas as pd
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
gauth = GoogleAuth()
gauth.LoadCredentialsFile(mycreds)
drive = GoogleDrive(gauth)
df = pd.DataFrame({'a':[1,2],'b':[2,3]})
f = drive.CreateFile({'id': '0B_6_uVX9biFuX0FJWFkt'}) #test.xlsx file
f.SetContentString(df)
f.Upload()
Run Code Online (Sandbox Code Playgroud)
AttributeError:'DataFrame'对象没有属性'encode'
我有一系列主要是英文的文本,但包含一些带有中文字符的短语。这里有两个例子:
s1 = "You say: ??. I say: ??"
s2 = "??, my friend, ????"
Run Code Online (Sandbox Code Playgroud)
我试图找到每个中文块,应用一个函数来翻译文本(我已经有办法进行翻译),然后替换字符串中的翻译文本。所以输出将是这样的:
o1 = "You say: hello. I say: goodbye"
o2 = "The answer, my friend, is blowing in the wind"
Run Code Online (Sandbox Code Playgroud)
通过这样做,我可以轻松找到汉字:
utf_line = s1.decode('utf-8')
re.findall(ur'[\u4e00-\u9fff]+',utf_line)
Run Code Online (Sandbox Code Playgroud)
...但我最终得到了所有汉字的列表,并且无法确定每个短语的开始和结束位置。