Pandas 将列类型从列表转换为 np.array

2024-04-03

我正在尝试将一个函数应用于 pandas 数据框,这样的函数需要两个 np.array 作为输入,并且它使用定义良好的模型来拟合它们。

关键是我无法从选定的列开始应用此函数,因为它们的“行”包含从 JSON 文件读取的列表,而不是 np.array。

现在,我尝试了不同的解决方案:

#Here is where I discover the problem

train_df['result'] = train_df.apply(my_function(train_df['col1'],train_df['col2']))

#so I've tried to cast the Series before passing them to the function in both these ways:

X_col1_casted = trai_df['col1'].dtype(np.array)
X_col2_casted = trai_df['col2'].dtype(np.array)

不起作用。

X_col1_casted = trai_df['col1'].astype(np.array)
X_col2_casted = trai_df['col2'].astype(np.array)

不起作用。

X_col1_casted = trai_df['col1'].dtype(np.array)
X_col2_casted = trai_df['col2'].dtype(np.array)

不起作用。

我现在想做的是一个漫长的过程,例如:

从未转换的列系列开始,将它们转换为 list(),对其进行迭代,将函数应用于 np.array() 单个元素,并将结果附加到临时列表中。完成后,我会将这个列表转换为一个新列。 (显然,我不知道它是否会起作用)

你们有人知道如何帮助我吗?

编辑: 为了清楚起见,我添加一个例子:

该函数假设有两个 np.array 作为输入。现在它有两个列表,因为它们是从 json 文件中检索的。情况是这样的:

col1        col2    result
[1,2,3]     [4,5,6]  [5,7,9]
[0,0,0]     [1,2,3]  [1,2,3]

显然,该函数不是求和函数,而是一个自身函数。暂时假设这个总和只能从数组开始,不能从列表开始,我该怎么办?

提前致谢


Use apply将每个元素转换为其等效数组:

df['col1'] = df['col1'].apply(lambda x: np.array(x))

type(df['col1'].iloc[0])
numpy.ndarray

Data:

df = pd.DataFrame({'col1': [[1,2,3],[0,0,0]]})
df
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Pandas 将列类型从列表转换为 np.array 的相关文章

随机推荐