从另一个系列解析 Pandas 系列

Rob*_*ert 6 python pandas

我试图解析一系列文本,使用一系列数字,如下面的代码,但我得到的只是一系列 NaN。

import numpy as np
import pandas as pd
numData = np.array([4,6,4,3,6])
txtData = np.array(['bluebox','yellowbox','greybox','redbox','orangebox'])
n = pd.Series(numData)
t = pd.Series(txtData)
x = t.str[:n]
print (x)
Run Code Online (Sandbox Code Playgroud)

输出是

0   NaN
1   NaN
2   NaN
3   NaN
4   NaN
Run Code Online (Sandbox Code Playgroud)

我希望输出是

0      blue
1    yellow
2      grey
3       red
4    orange
Run Code Online (Sandbox Code Playgroud)

是否有捷径可寻。

Ch3*_*teR 3

你可以pd.Series.str.slice

t.str.slice(stop=-3)
# short hand for this is t.str[:-3]
0      blue
1    yellow
2      grey
3       red
4    orange
dtype: object
Run Code Online (Sandbox Code Playgroud)

或者将其转换numData迭代器usingiter和 useslice

it = iter(numData)
t.map(lambda x:x[slice(next(it))])
0      blue
1    yellow
2      grey
3       red
4    orange
dtype: object
Run Code Online (Sandbox Code Playgroud)