繁体   English   中英

将pandas数据帧的字符串转换为int的numpy数组

[英]convert pandas dataframe of strings to numpy array of int

我的输入是一个带有字符串的pandas数据帧:

>>> data
218.0                 
221.0                 
222.0                 
224.0    71,299,77,124
227.0     50,283,81,72
229.0              
231.0           84,349
233.0                 
235.0                 
240.0           53,254
Name: Q25, dtype: object

现在我想要一个形状(.reshape(-1,2))numpy数组的int为每一行像这样:

>>> data
218.0                      [] 
221.0                      []
222.0                      []
224.0    [[71,299], [77,124]]
227.0     [[50,283], [81,72]]
229.0                      []
231.0              [[84,349]]
233.0                      []
235.0                      []
240.0              [[53,254]]
Name: Q25, dtype: object

我不知道如何通过矢量操作到达那里。 有人可以帮忙吗?

您可以使用apply ,但这不是矢量操作

In [277]: df.val.fillna('').apply(
         lambda x: np.array(x.split(','), dtype=int).reshape(-1, 2) if x else [])
Out[277]:
0                        []
1                        []
2                        []
3    [[71, 299], [77, 124]]
4     [[50, 283], [81, 72]]
5                        []
6               [[84, 349]]
7                        []
8                        []
9               [[53, 254]]
Name: val, dtype: object

不是很酷,但很准确。

def f(x):
    if x != '':
        x = list(map(int, x.split(',')))
        return list(map(list, zip(x[::2], x[1::2])))
    else:
        return []

s.apply(f)

0                        []
1    [[71, 299], [77, 124]]
2               [[84, 349]]
dtype: object

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM