Python Pandas - 返回根据值推断出的字符串类型


要返回根据值推断出的字符串类型,请在 Pandas 中使用index.inferred_type 属性。

首先,导入所需库 −

import pandas as pd
import numpy as np

创建索引。对于 NaN,我们已经使用了 numpy 库 −

index = pd.Index(['Car','Bike', np.nan,'Car',np.nan, 'Ship', None, None])

显示索引 −

print("Pandas Index...\n",index)

返回根据值推断出的字符串类型 −

print("\nThe inferred type...\n",index.inferred_type)

示例

以下是代码 −

import pandas as pd
import numpy as np

# Creating the index
# For NaN, we have used numpy library
index = pd.Index(['Car','Bike', np.nan,'Car',np.nan, 'Ship', None, None])

# Display the index
print("Pandas Index...\n",index)

# Return an array representing the data in the Index
print("\nArray...\n",index.values)

# Check if the index is having NaNs
print("\nIs the Pandas index having NaNs?\n",index.hasnans)

# Return the dtype of the data
print("\nThe dtype object...\n",index.dtype)

# Return a string of the type inferred from the values
print("\nThe inferred type...\n",index.inferred_type)

输出

这将生成以下代码 −

Pandas Index...
Index(['Car', 'Bike', nan, 'Car', nan, 'Ship', None, None], dtype='object')

Array...
['Car' 'Bike' nan 'Car' nan 'Ship' None None]

Is the Pandas index having NaNs?
True

The dtype object...
object

The inferred type...
Mixed

更新于: 2021-10-13

103 次浏览

Kickstart 您的 职业生涯

通过完成课程获得认证

开始学习
广告