【问题标题】:converting pd.Series of strings into ndarray将 pd.Series 字符串转换为 ndarray
【发布时间】:2019-02-02 21:25:15
【问题描述】:

我从 pandas 列中提取一个单词数组:

X = np.array(tab1['word'])

X 示例:array(['dog', 'cat'], dtype=object)

X 是 665 个字符串的 pandas 系列。 然后我将每个单词转换为 (1,270) 的 ndarray

for i in range(len(X)):
    tmp = X[i]
    z = func(tmp) #function that returns ndarray of (1,270)
    X[i] = z

我的最终目标是获得形状的 Ndarray: (665, 270) 但是我得到了这个形状:(665,) 当我尝试时,我也无法重塑它:X.reshape(665,270) 我收到此错误:

ValueError: cannot reshape array of size 665 into shape (665,270)

func(word) 函数可以是任何函数,例如:

def func(word):
    a = np.arange(0,270)
    a = a.reshape(1,270)
    return a

关于为什么会这样的任何想法?

【问题讨论】:

  • 请发布一个最小的、可验证的和完整的示例。目前我们必须猜测问题是什么
  • 我添加了更多细节

标签: python pandas numpy reshape2


【解决方案1】:

问题在于通过一个转换函数将 Pandas 系列字符串转换为 NumPy 数组,该函数在给定字符串输入的情况下返回一个 (1, n) 数组。

解决办法如下:

import pandas as pd
import numpy as np

# You have a series of strings
X = pd.Series(['aaa'] * 665)

# You have a transformative func that returns a (1, n) np.array
def func(word, n=270):
    return np.zeros((1, n))

# You apply the function to the series and vertically stack the results
Xs = np.vstack(X.apply(func))

# You check for the desidered shape
print(Xs.shape)

【讨论】:

    【解决方案2】:

    下面的重点是:

    z = list(func(tmp)) # converting returned value from func to a list
    

    result = np.array([x for x in X.values])
    

    这是我的完整测试代码:

    import numpy as np
    import pandas as pd
    
    
    def func(tmp):
        return np.array([t for t in tmp])
    
    
    X = pd.Series({'a': 'abc', 'x': 'xyz', 'j': 'jkl', 'z': 'zzz'})
    for i in range(len(X)):
        tmp = X[i]
        z = list(func(tmp)) # converting returned value from func to a list
        X[i] = z
    
    result = np.array([x for x in X.values])
    

    然后在控制台输入 result,你会看到它是一个 (4, 3) ndarray。

    In[3] result
    Out[3]: 
    array([['a', 'b', 'c'],
           ['x', 'y', 'z'],
           ['j', 'k', 'l'],
           ['z', 'z', 'z']], dtype='<U1')
    

    【讨论】:

      猜你喜欢
      • 2014-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-14
      • 1970-01-01
      • 1970-01-01
      • 2021-10-05
      • 1970-01-01
      相关资源
      最近更新 更多