pandas 面试题挑战六

------------恢复内容开始------------

从Series的字符串中过滤出email地址

现有Series如下:

emails = pd.Series(['buying books at amazom.com', 'rameses@egypt.com', 'matt@t.co', 'narendra@modi.com'])

解决办法:

import re
pattern ='[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}'
mask = emails.map(lambda x: bool(re.match(pattern, x)))
emails[mask]

结果如下:

1    rameses@egypt.com
2            matt@t.co
3    narendra@modi.com
dtype: object

把一个Series按照另外一个Series的元素进行分组,并求均值。

现有两个Series如下:

fruit = pd.Series(np.random.choice(['apple', 'banana', 'carrot'], 10))
weights = pd.Series(np.linspace(1, 10, 10))
print(weights)
print(fruit)

输出:

0     1.0
1     2.0
2     3.0
3     4.0
4     5.0
5     6.0
6     7.0
7     8.0
8     9.0
9    10.0
dtype: float64
0    banana
1    banana
2    carrot
3     apple
4    carrot
5     apple
6    banana
7     apple
8     apple
9    banana
dtype: object

现在把weights中的元素按照fruit的元素为进行分组,并求平均值
解决办法:

weights.groupby(fruit).mean()

输出:

apple     6.75
banana    5.00
carrot    4.00
dtype: float64

求两个Series的模值差

现有两个Series如下:

p = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
q = pd.Series([10, 9, 8, 7, 6, 5, 4, 3, 2, 1])

其实就是把p,q看成是两个向量,然后可以方便的使用np.linalg.norm()来解决问题。

p = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
q = pd.Series([10, 9, 8, 7, 6, 5, 4, 3, 2, 1])
np.linalg.norm(p-q)

结果如下:

18.16590212458495

找到出现最少的字符,并使用它填充字符串的空白位置

现有Series如下:

my_str = 'dbc deb abed gade'

找到出现最少的字符,并使用它填充字符串的空白位置。
解决如下:

ser = pd.Series(list('dbc deb abed gade'))
freq = ser.value_counts()

least_freq = freq.dropna().index[-1]
"".join(ser.replace(' ', least_freq))

结果如下:

'dbccdebcabedcgade'

创建Series,索引按照week 递进,值为随机数,范围1 - 10

产生类似的输出:

 

 解决方式如下:

ser = pd.Series(np.random.randint(1,10,10),pd.date_range('2000-01-01', periods=10, freq='7D'))
ser
重点解读:
pd.date_range('2000-01-01', periods=10, freq='7D') 代表从'2000-01-01'开始,periods=10意味一共产生10个数据,freq='7D'频率是7天,D代表天。
posted @ 2020-12-03 15:50  Tracydzf  阅读(172)  评论(0编辑  收藏  举报