python - 如果另一列数据在列表中, Pandas 会更改一列数据

标签 python pandas

我在这样的数据框中有一些数据:

COLUMNS Point,x,y,z,Description,Layer,Date
1,224939.203,1243008.651,1326.774,F,C-GRAD-FILL,09/22/18 07:24:34,
1,225994.242,1243021.426,1301.772,BS,C-GRAD-FILL,09/24/18 08:24:18,
451,225530.332,1243016.186,1316.173,GRD,C-TOE,10/02/18 11:49:13,
452,225522.429,1242996.017,1319.168,GRD,C-TOE KEY,10/02/18 11:49:46,

我想尝试检查一个字符串列表以查看它是否匹配,然后更改另一个列的值。

myList = ["BS", "C"]
if df['Description'].isin(myList)) == True:
     df['Layer']="INLIST"
     df['Date']="1/1/2018'

最佳答案

使用掩码 pd.DataFrame.loc :

mask = df['Description'].isin(['BS', 'C'])
df.loc[mask, 'Layer'] = 'INLIST'
df.loc[mask, 'Date'] = '1/1/2018'

或者,使用 pd.Series.mask :

mask = df['Description'].isin(['BS', 'C'])
df['Layer'].mask(mask, 'INLIST', inplace=True)
df['Date'].mask(mask, '1/1/2018', inplace=True)

请注意,您可能应该将日期存储为 datetime 对象,例如pd.Timestamp('2018-01-01'),或通过 pd.to_datetime 转换您的系列.通常不需要 Python 级别的循环。

关于python - 如果另一列数据在列表中, Pandas 会更改一列数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53023736/

相关文章:

python - 模块未找到错误 : No module named 'pandas' - when I have pandas already installed

python - 无法保留内存块,在 python 中导入 json 错误

python - 如何获取列中的数据,其名称保存在python的另一列中

python - 从 Pandas Column 获取每行一个值的列表

python - 将文件加载到 2d numpy 数组中的有效方法

python - 运行时错误 : The following handlers are available to decode the pixel data however they are missing required dependencies: GDCM (req. GDCM)

python - python 项目的 sonarqube 没有显示任何测试覆盖率

python - 重复数据帧中的行 n 次

python - 将 pandas 系列中的值分开并将它们全部堆叠到列表中?

python - django:禁用某一特定字段的tinymce