python - Pandas :从列列表中替换值列表

标签 python pandas replace

我有很多行、很多列的数据框,它们具有需要替换的不同“占位符”值(在列的子集中)。我已经在论坛中阅读了很多使用嵌套列表或字典的示例,但没有运气变化..

# A test dataframe
df = pd.DataFrame({'Sample':['alpha','beta','gamma','delta','epsilon'],
                  'element1':[1,-0.01,-5000,1,-2000], 
                  'element2':[1,1,1,-5000,2], 
                  'element3':[-5000,1,1,-0.02,2]})

# List of headings containing values to replace
headings = ['element1', 'element2', 'element3']

我正在尝试做这样的事情(显然这行不通):

 # If any rows have value <-1, NaN
 df[headings].replace(df[headings < -1], np.nan)

 # If a value is between -1 and 0, make a replacement
 df[headings].replace(df[headings < 0 & headings > -1], 0.05)

那么,是否有更好的方法可以使用循环或花哨的 pandas 技巧来完成此任务?

最佳答案

您可以将Sample列设置为索引,然后根据条件替换整个数据框上的值:

df = df.set_index('Sample')
df[df < -1] = np.nan
df[(df < 0) & (df > -1)] = 0.05

给出:

#           element1    element2    element3
#  Sample           
#   alpha       1.00        1.0          NaN
#    beta       0.05        1.0         1.00
#   gamma        NaN        1.0         1.00
#   delta       1.00        NaN         0.05
# epsilon        NaN        2.0         2.00

关于python - Pandas :从列列表中替换值列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38288711/

相关文章:

python - 使用 BS4 抓取雅虎财经统计数据的网页

python - Nuke自己的python版本,如何安装、添加或包装新模块?

python - HDFStore 启动停止不起作用

python - 没有重复的背包 : Maximum Amount of Gold - Python code question

python - 如何使用 Altair 进行注释?

python - Pandas 命名聚合不适用于 resample agg

python - 如何从数据框中的列中提取强标签并附加或替换该单元格?

regex - [Regex]::Replace() 和 -replace 之间有什么区别?

python - 如何替换 r'\xb 0' with r'\260'

powershell - 在 Powershell 中,如何替换包含问号的字符串?