根据条件替换Pandas Dataframe中的值

时间:2018-04-16 12:32:48

标签: python pandas dataframe replace conditional-statements

我有一个带有一些数值的数据框列。我希望根据给定条件将这些值替换为1和0。条件是如果该值高于列的平均值,则将数值更改为1,否则将其设置为0.

以下是我现在的代码:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

dataset = pd.read_csv('data.csv')
dataset = dataset.dropna(axis=0, how='any')

X = dataset.drop(['myCol'], axis=1)
y = dataset.iloc[:, 4:5].values

mean_y = np.mean(dataset.myCol)

目标是数据框y。你是这样的:

      0
0    16
1    13
2    12.5
3    12

等等。 mean_y等于3.55。 因此,我需要将大于3.55的所有值变为1,其余为0。

我应用了这个循环,但没有成功:

for i in dataset.myCol:
    if dataset.myCol[i] > mean_y:
        dataset.myCol[i] = 1
    else:
        dataset.myCol[i] = 0

输出如下:

      0
0    16
1    13
2    0
3    12

我做错了什么?有人可以解释一下我的错误吗?

谢谢!

2 个答案:

答案 0 :(得分:5)

尝试这种矢量化方法:

dataset.myCol = np.where(dataset.myCol > dataset.myCol.mean(), 1, 0)

答案 1 :(得分:2)

将布尔掩码转换为整数 - True转换为1,将False转换为0

print (dataset.myCol > mean_y)
0     True
1    False
2    False
3    False
Name: myCol, dtype: bool

dataset.myCol = (dataset.myCol > mean_y).astype(int)
print (dataset)
   myCol
0      1
1      0
2      0
3      0

对于您的aproach,不建议使用,因为列和索引值对设置值的缓慢需要iterrows

for i, x in dataset.iterrows():
    if dataset.loc[i, 'myCol'] > mean_y:
        dataset.loc[i, 'myCol'] = 1
    else:
        dataset.loc[i, 'myCol'] = 0