识别Pandas DataFrame列的类型为numpy的DataFrame值数组

问题描述 投票:1回答:2

[我正在编写连接使用Pandas DataFrames和Numpy数组的库的粘合代码,并且在确定最初由Pandas Dataframes创建的Numpy数组中哪些列是'object / string'时遇到了一些问题。

import pandas as pd
test_df = pd.DataFrame({"a": [1, 2, 3], "b": ["one", "two", "three"]})
test_arr = test.values
test_df2 = pd.DataFrame(test_arr)

test_df.dtypes
# a     int64, b    object

test_df2.dtypes

# 0    object, 1    object

我希望test_df2.dtypes是int64&对象,而不是两个对象。

如何使用numpy数组'test_arr'中的信息找到原始Pandas DataFrame列的数据类型?

我可以使用以下方法实现所需的行为,但是想知道是否有更有效/更优雅的解决方案?我也担心这种方法可能很脆弱:

test_df3 = pd.DataFrame(test_arr).apply(
lambda x: pd.to_numeric(x, errors="ignore"), axis=1
)

编辑-使用test_df数据类型的一些解决方案。我无权访问此文件,也无法控制如何创建test_arr。我想仅使用test_arr查找test_df的数据类型。

arrays pandas numpy dataframe types
2个回答
1
投票
您可以创建具有test_df2 dtypes的test_df列的字典,并在df.astype中使用该字典

0
投票
您可以做出类似的事情:
© www.soinside.com 2019 - 2024. All rights reserved.