我有一个看起来像这样的数据框。
Name |
Age |
John |
20.5 |
Alice |
39.1 |
Pam |
41.0 |
203921 |
Hope |
我想创建一个名为“Name_Type”的新列,其返回如下:
Name |
Name_Type |
John |
True |
Alice |
True |
Pam |
True |
203921 |
False |
Age |
Age_Type |
20.5 |
True |
39.1 |
True |
41.0 |
True |
Hope |
False |
我想检查名称列是否是字符串。我将对 Age 执行相同的操作,检查它是否为 FLOAT。
我希望这适用于您的情况:
df = pd.DataFrame({'Name':['John', 'Alice', 'Pam', 203921], 'Age':[20.5, 39.1, 41.0, 'Hope']})
df['Name_Type'] = [True if type(x) == str else False for x in df.Name]
df['Age_Type'] = [True if type(x) == float else False for x in df.Age]
print(df)
Result:
Name Age Name_Type Age_Type
0 John 20.5 True True
1 Alice 39.1 True True
2 Pam 41.0 True True
3 203921 Hope False False
当所有值都是字符串时,此解决方案应该有效:
df = pd.DataFrame({'Name':['John', 'Alice', 'Pam', '203921'], 'Age':['20.5', '39.1', '41.0', 'Hope']})
def is_float(x):
try:
float(x)
return True
except:
return False
df['Name_Type'] = ~df.Name.str.isnumeric()
df['Age_Type'] = df.Age.apply(is_float)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)