pandas 用n个元素创建一个序列(顺序或中间) [英] pandas create a series with n elements (sequential or randbetween)
本文介绍了 pandas 用n个元素创建一个序列(顺序或中间)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建pandas
系列.
该系列的一列应包含n个序号. [1, 2, 3, ..., n]
One column of the series should contain n sequential numbers. [1, 2, 3, ..., n]
一列应包含k
和k+100
之间的随机数.
One column should contain random numbers between k
and k+100
.
一列应包含列表中字符串之间的随机选择. ['A', 'B', 'C', ... 'Z']
One column should contain random selection between strings in a list. ['A', 'B', 'C', ... 'Z']
推荐答案
可以有很多解决方案.在代码块(#
)的注释中,您会找到一些链接以获取更多信息:
There can be a lot of solutions. In the comments of the code block (#
) you will find a few links for more information:
import pandas as pd
import numpy as np
import random
import string
k = 5
N = 10
#http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html
#http://stackoverflow.com/a/2257449/2901002
df = pd.DataFrame({ 'A' : range(1, N + 1 ,1),
'B' : np.random.randint(k, k + 100 , size=N),
'C' : pd.Series(random.choice(string.ascii_uppercase) for _ in range(N)) })
print df
# A B C
#0 1 60 O
#1 2 94 L
#2 3 10 W
#3 4 94 X
#4 5 60 O
#5 6 20 K
#6 7 58 Y
#7 8 40 I
#8 9 49 X
#9 10 65 S
Numpy 解决方案:
import pandas as pd
import numpy as np
k = 5
N = 10
alphabet = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
#http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.choice.html
df = pd.DataFrame({ 'A' : range(1, N + 1 ,1),
'B' : np.random.randint(k, k + 100 , size=N),
'C' : np.random.choice(np.array(alphabet, dtype="|S1"), N) })
print df
# A B C
#0 1 16 U
#1 2 76 X
#2 3 101 N
#3 4 61 F
#4 5 52 J
#5 6 62 A
#6 7 99 L
#7 8 23 N
#8 9 75 D
#9 10 16 Q
这篇关于 pandas 用n个元素创建一个序列(顺序或中间)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文