我是python的新手,正在努力操纵pandas库中的数据.我有一个像这样的pandas数据库:
Year Value
0 91 1
1 93 4
2 94 7
3 95 10
4 98 13
Run Code Online (Sandbox Code Playgroud)
并希望完成创建具有空值的行的缺失年份,如下所示:
Year Value
0 91 1
1 92 0
2 93 4
3 94 7
4 95 10
5 96 0
6 97 0
7 98 13
Run Code Online (Sandbox Code Playgroud)
我怎么用Python做到这一点?(我想这样做,所以我可以绘制值而不会跳过多年)
我正在尝试创建一个具有复杂数据类型的表。下面列出了数据类型。
大批
地图
数组<映射<字符串,字符串>>
我正在尝试创建 3 类型的数据结构。是否有可能在 Hive 中创建?我的表 DDL 如下所示。
create table complexTest(names array<String>,infoMap map<String,String>, deatils array<map<String,String>>)
row format delimited
fields terminated by '/'
collection items terminated by '|'
map keys terminated by '='
lines terminated by '\n';
Run Code Online (Sandbox Code Playgroud)
我的示例数据如下所示。
Abhieet|Test|Complex/Name=abhi|age=31|Sex=male/Name=Test,age=30,Sex=male|Name=Complex,age=30,Sex=female
Run Code Online (Sandbox Code Playgroud)
无论我从表中查询数据,我都会得到以下值
["Abhieet"," Test"," Complex"] {"Name":"abhi","age":"31","Sex":"male"} [{"Name":null,"Test,age":null,"31,Sex":null,"male":null},{"Name":null,"Complex,age":null,"30,Sex":null,"female":null}]
Run Code Online (Sandbox Code Playgroud)
这不是我所期待的。如果数据类型可能,请帮我找出应该是什么 DDLarray< map < String,String>>
我有单列的多索引数据框.我想基于该数据帧绘制堆积条形图.数据如下:
df= pd.DataFrame(index=pd.MultiIndex([[1,2,3],['open','closed']],[[0,0,1,1,2,2],[0,1,0,1,0,1]]))
df['id']=[23,6,12,4,31,16]
df
id
state
1 closed 23
open 6
2 closed 12
open 4
3 closed 31
open 16
Run Code Online (Sandbox Code Playgroud) 有没有办法应用bincount“axis = 1”?所需的结果将与列表理解相同:
import numpy as np
A = np.array([[1,0],[0,0]])
np.array([np.bincount(r,minlength = np.max(A) + 1) for r in A])
#array([[1,1]
# [2,0]])
Run Code Online (Sandbox Code Playgroud) 我有一个数据框df,其中一列名为"Num_of_employees",其值为50-100,200-500等.我发现数据中的值很少.无论员工人数为1-10,数据均为10月1日.此外,无论价值应该是11-50,数据都是11月50日.我如何使用熊猫纠正这个问题?
数字系列具有很好的舍入方法,用于舍入到10的幂,例如
>>> pd.Series([11,16,21]).round(-1)
0 10
1 20
2 20
dtype: int64
Run Code Online (Sandbox Code Playgroud)
舍入到最接近的5(或10的其他非幂)是否有相当好的语法?我有点希望round可以采用非整数值吗?
我有几个 Pandas 数据系列,想训练这些数据映射到输出 df["output"]。
到目前为止,我已将系列合并为一个,并用逗号分隔每个系列。
df = pd.read_csv("sourcedata.csv")
sample = df["catA"] + "," + df["catB"] + "," + df["catC"]
def my_tokenizer(s):
return s.split(",")
vect = CountVectorizer()
vect = CountVectorizer(analyzer='word',tokenizer=my_tokenizer, ngram_range=(1, 3), min_df=1)
train = vect.fit_transform(sample.values)
lf = LogisticRegression()
lfit = lf.fit(train, df["output"])
pred = lambda x: lfit.predict_proba(vect.transform([x]))
Run Code Online (Sandbox Code Playgroud)
问题是这是一个词袋方法,没有考虑
- 每个类别中的唯一顺序。(“橙香蕉”与“香蕉橙”不同)
-文本是一个类别的含义与另一个类别不同(一个类别中的“美国”可能意味着原产国与目的地国家/地区)
例如,整个字符串可以是:
pred("US, Chiquita Banana, China")
A 类:原产国
B 类:公司和水果类型(订单很重要)
C 类:目的地
我目前的做法是忽略任何类型的排序,并且出于某种原因还在我的功能名称中生成了额外的空格(这会使事情更加混乱):
In [1242]: vect.get_feature_names()[0:10]
Out[1242]:
[u'',
u' ',
u' ',
u' ',
u' ',
u' ',
u' US', …Run Code Online (Sandbox Code Playgroud) 我有一个字典列表,如下所示:
L=[
{
"timeline": "2014-10",
"total_prescriptions": 17
},
{
"timeline": "2014-11",
"total_prescriptions": 14
},
{
"timeline": "2014-12",
"total_prescriptions": 8
},
{
"timeline": "2015-1",
"total_prescriptions": 4
},
{
"timeline": "2015-3",
"total_prescriptions": 10
},
{
"timeline": "2015-4",
"total_prescriptions": 3
}
]
Run Code Online (Sandbox Code Playgroud)
这基本上是SQL查询的结果,当给出开始日期和结束日期时,给出从开始日期到结束月份的每个月的总处方数.然而,对于处方计数为0的月份(2月) 2015),它完全跳过那个月.是否可以使用pandas或numpy来改变这个列表,以便为缺失的月份添加一个条目,其中0作为总处方如下:
[
{
"timeline": "2014-10",
"total_prescriptions": 17
},
{
"timeline": "2014-11",
"total_prescriptions": 14
},
{
"timeline": "2014-12",
"total_prescriptions": 8
{
"timeline": "2015-1",
"total_prescriptions": 4
},
{
"timeline": "2015-2", # 2015-2 to be inserted for missing month
"total_prescriptions": 0 # 0 …Run Code Online (Sandbox Code Playgroud) 我写了以下函数
(defn insert-block
"Given a block, coordinate and playfield, returns the altered playfield.
Does not check for collisions."
[[x y] block playfield]
(let [blocksize (count block)
insertion (fn [a b] (vector (block a) (playfield b)))
block-indicies (range 0 blocksize)
field-indicies (range y (+ y blocksize))]
(map insertion block-indicies field-indicies)))
Run Code Online (Sandbox Code Playgroud)
块和游戏区域都是向量的向量.出于某种原因,每次调用此函数时,都会出现以下错误:
#<ClassCastException java.lang.ClassCastException: clojure.lang.LazySeq cannot be cast to clojure.lang.IFn>
Run Code Online (Sandbox Code Playgroud)
该函数已经从我的代码中简化了一点 - "插入"在原始版本中更复杂,但无论如何我得到相同的错误.这让我感到疯狂 - 有没有人有任何想法?
编辑:我一直用[2]为[xy]和[[0 0 0] [0 1 0] [1 1 1]]测试它.Playfield太大而无法在此处粘贴,但它是包含整数的26个向量的向量,长度为14.
EDIT2:这是playfield矢量.
[[1 1 1 1 1 1 1 …Run Code Online (Sandbox Code Playgroud) def len_link(lst):
"""Returns the length of the link.
>>> lst = link(1, link(2, link(3, link(4))))
>>> len_link(lst)
4
>>> len_link(empty)
0
"""
Run Code Online (Sandbox Code Playgroud)
嗨,如果有人可以提供帮助,我很难理解如何找到链表的长度,我将不胜感激。
我有下面的代码段我想列出词频,在那里first_text和second_text有.tex文件:
from sklearn.feature_extraction.text import CountVectorizer
training_documents = (first_text, second_text)
vectorizer = CountVectorizer()
vectorizer.fit_transform(training_documents)
print "Vocabulary:", vectorizer.vocabulary
Run Code Online (Sandbox Code Playgroud)
运行脚本时,得到以下信息:
File "test.py", line 19, in <module>
vectorizer.fit_transform(training_documents)
File "/usr/local/lib/python2.7/site-packages/sklearn/feature_extraction/text.py", line 817, in fit_transform
self.fixed_vocabulary_)
File "/usr/local/lib/python2.7/site-packages/sklearn/feature_extraction/text.py", line 752, in _count_vocab
for feature in analyze(doc):
File "/usr/local/lib/python2.7/site-packages/sklearn/feature_extraction/text.py", line 238, in <lambda>
tokenize(preprocess(self.decode(doc))), stop_words)
File "/usr/local/lib/python2.7/site-packages/sklearn/feature_extraction/text.py", line 115, in decode
doc = doc.decode(self.encoding, self.decode_error)
File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode …Run Code Online (Sandbox Code Playgroud) 我正在将数据从一张表加载到熊猫,然后将该数据插入到新表中。但是,我看到的是字节数组,而不是普通的字符串值。
bytearray(b'TM16B0I8') 它应该是 TM16B0I8
我在这里做错了什么?
engine_str = 'mysql+mysqlconnector://user:pass@localhost/db'
engine = sqlalchemy.create_engine(engine_str, echo=False, encoding='utf-8')
connection = engine.connect()
th_df = pd.read_sql('select ticket_id, history_date', con=connection)
for row in th_df.to_dict(orient="records"):
var_ticket_id = row['ticket_id']
var_history_date = row['history_date']
query = 'INSERT INTO new_table(ticket_id, history_date)....'
Run Code Online (Sandbox Code Playgroud) 假设我有一个大字典d,我想显示一些随机元素(如果我尝试__repr__整个事情,我的终端会崩溃).
在Python 2中我会打电话d.items()[0]; 我在Python 3中做什么...是Pythonic的等价物next(iter(d.items()))?
python ×9
pandas ×7
numpy ×3
python-3.x ×3
dictionary ×2
scikit-learn ×2
arrays ×1
casting ×1
clojure ×1
dataframe ×1
hive ×1
ipython ×1
linked-list ×1
list ×1
mysql ×1
plot ×1
python-2.7 ×1
row ×1
sqlalchemy ×1