首页 > 解决方案 > 根据 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')

标签: pythonpandasnumpydataframe

解决方案


仅用于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') 

推荐阅读