繁体   English   中英

如何根据 Pandas 数据框中的另一列值添加列?

[英]How to add column based on another column value in Pandas dataframe?

我如何获取数据框,如下所示:

      col1    col2
row0   abc      3
row1   bcd     2.4

并生成一个带有新列的数据框,该列的值基于 col2,是 number 中是否有点,如下所示:

      col1    col2    col3
row0   abc      3     No dot
row1   bcd     2.4    Has dot

任何帮助表示赞赏。

以下应该工作:

df['col3']=df['col2'].apply(lambda x: 'No dot' if int(x)==x else 'Has dot')

numpy.whereSeries.str.contains numpy.where使用,因为. 是特殊的正则表达式字符通过\\转义它:

df['col3'] = np.where(df['col2'].astype(str).str.contains('\.'), 'Has dot', 'No dot')

或者使用regex=False参数:

df['col3'] = np.where(df['col2'].astype(str).str.contains('.', regex=False), 
                      'Has dot', 'No dot')

print (df)

     col1 col2     col3
row0  abc    3   No dot
row1  bcd  2.4  Has dot

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM