嗨,我正在尝试用固定值填充新列,如果满足条件的话。但如果条件不满足,我也会得到值。(对于某些行)我哪里错了?如果“id”为空,则“type”中需要留空,否则列“id1”的字符串“A2A”数据类型为object。当我把它转换成字符串时,它给出了错误。尽管我们在“ID1”中看到了空行。它显示错误“无法对浮点数执行操作”
代码:
df1['type'] = np.where((df1['ID1'].isnull()) , np.nan,'A2A')输入:
ID1
2
3
4输出:
ID1 type
nan
A2A
A2A
2 A2A
3 A2A
nan
nan
4 A2A
A2A预期输出:
ID1 type
2 A2A
3 A2A
4 A2A发布于 2020-06-26 19:17:01
您可以尝试这样做:
确保将多个空格删除为仅为空
df = pd.DataFrame([None, np.nan, '','','',2,3,'',''])
df = df.replace(r'^\s*$', '', regex=True)
df.fillna('', inplace=True)选项1:您可以使用pandas .apply
df["type"] = df.apply(lambda x: "A2A" if x[0] else '',axis=1)选项2:无轴:
df["type"] = df[0].apply(lambda x: "A2A" if x else '')选项3:您也可以使用 np.where**:**
df["type"] = np.where(df[0], "A2A", '')选项4:将整个列转换为字符串格式并检查值
df[0].apply(lambda x: "A2A" if str(x).lower().strip() not in ["none","nan",""] else '')输入:
0
0 None
1 NaN
2
3
4
5 2
6 3
7
8 输出:
0 type
0
1
2
3
4
5 2 A2A
6 3 A2A
7
8 https://stackoverflow.com/questions/62593523
复制相似问题