我正在尝试根据Python中的不同条件更改数据框的值。
这是我的数据集的示例
df1=pd.DataFrame(np.array([['A',1, 2, 'NaN'], ['B',-4, 5, -6], ['C', 7, 0, 9]]), columns=['详细信息','a', 'b', 'c'])
我想更改以下值,
df1=pd.DataFrame(np.array([['A','大', '大', '无数据'], ['B','小', '大', '小'], ['C','大', '零', '大']]),columns=['详细信息','a', 'b', 'c'])
我尝试使用以下行,但这不起作用。我想知道是否有任何简单的方法可以做到这一点。提前致谢
df1[df1.columns[1:]] = df1.iloc[:,1:].where(df1.iloc[:,1:] >0 ,'大')
最佳答案
使用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')
关于python - 根据pandas中的条件更改数据框的所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64820463/