python - 根据 pandas 中的条件更改数据框的所有值
问题描述
我正在尝试根据 python 中的不同条件更改数据框的值。
这是我的数据集的示例
df1=pd.DataFrame(np.array([['A',1, 2, 'NaN'], ['B',-4, 5, -6], ['C',7, 0, 9]]), columns=['Details','a', 'b', 'c'])
我想改变以下值,
df1=pd.DataFrame(np.array([['A','big', 'big', 'No data'], ['B','small', 'big', 'small'], ['C','big', 'zero', 'big']]),columns=['Details','a', 'b', 'c'])
我尝试使用以下行,但这不起作用。我想知道是否有任何简单的方法可以做到这一点。提前致谢
df1[df1.columns[1:]] = df1.iloc[:,1:].where(df1.iloc[:,1:] >0 ,'big')
解决方案
仅用于numpy.select
选定的列:
c = ['a','b','c']
#if necessary convert to numeric
df1[c] = df1[c].astype(float)
df1[c] = np.select([df1[c] > 0, df1[c] <= 0], ['big','small'], default='No data')
print (df1)
Details a b c
0 A big big No data
1 B small big small
2 C big small big
如果需要先测试所有列:
df1.iloc[:, 1:] = np.select([df1.iloc[:, 1:] > 0,
df1.iloc[:, 1:] <= 0], ['big','small'], default='No data')
推荐阅读
- javascript - 不同语言的响应API JSON
- javascript - 有什么方法可以访问 JS 文件中的 Django 模板变量和 URL 标记,以便用户无法检查数据和链接?
- python - 如何从另一个数据帧有条件地更新数据帧
- node.js - 捕获 1:1 用户之间的视频会议并广播到 rtmp url
- makefile - Makefile 包含 .env 与 MAKEFILE_LIST 冲突
- python - 有没有办法表示具有无限非零项的离散信号(Python)
- css - Flexbox中孙子的绝对定位
- npm-install - 所需的 JS 依赖 "@silvia-odwyer/photon" 不可用 -- ClojureScript -- Node.js -- npm -- yarn
- c# - c# 演示的新手 Lucene 问题“找不到类型或命名空间‘StandardAnalyzer’”
- spring-integration - Java:MQTT MessageProducerSupport to Flux