从另一个Series解析Pandas Series

6

我试图使用下面的代码中的一系列数字来解析一系列文本,但返回的结果只是一系列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)

输出结果为

0   NaN
1   NaN
2   NaN
3   NaN
4   NaN

我希望输出结果如下:

0      blue
1    yellow
2      grey
3       red
4    orange

有没有简单的方法来完成这个任务。

3个回答

4

如果实际情况下你无法截掉最后三个字符并需要依赖你的切片范围,你可以使用简单的列表推导式。如果数据不能保证全部是字符串,或者end可能超过字符串的长度,则需要错误处理。

pd.Series([x[:end] for x,end in zip(t,n)], index=t.index)

0      blue
1    yellow
2      grey
3       red
4    orange
dtype: object

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

或者使用iternumData转换为一个迭代器,并使用slice

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

2
numdata_iter = iter(numData)
x = t.apply(lambda text: text[:next(numdata_iter)])

我们将 numData 转换为迭代器,然后对于 apply 中的每个切片,调用 next

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接