stat.md 2.4 KB
Newer Older
F
fix bug  
feilong 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
# pandas dataframe之apply

apply的使用


## template

```python
import pandas as pd
import numpy as np

def add_val(num):
    if num > 0:
        return 1
    else:
        return 0


if __name__ == '__main__':
    data = {
        'cloumn_one': pd.Series(np.random.randint(-10, 10, size=5)),
        'cloumn_two': pd.Series(np.random.randint(0, 10, size=5)),
        'cloumn_three': pd.Series(np.random.randint(0, 10, size=5))
    }
    data_df = pd.DataFrame(data)

    data_df['label_one'] = data['cloumn_one'].apply(add_val)

    print(data_df)
```

## 答案

```python
import pandas as pd
import numpy as np

if __name__ == '__main__':
    data = {
        'cloumn_one': pd.Series(np.random.randint(-10, 10, size=5)),
        'cloumn_two': pd.Series(np.random.randint(0, 10, size=5)),
        'cloumn_three': pd.Series(np.random.randint(0, 10, size=5))
    }
    data_df = pd.DataFrame(data)

    data_df['label_one'] = data['cloumn_one'].apply['num'>1]

    print(data_df)
```

## 选项

### A

```python
import pandas as pd
import numpy as np

def add_val(num):
    if num > 0:
        return 1
    else:
        return 0


if __name__ == '__main__':
    data = {
        'cloumn_one': pd.Series(np.random.randint(-10, 10, size=5)),
        'cloumn_two': pd.Series(np.random.randint(0, 10, size=5)),
        'cloumn_three': pd.Series(np.random.randint(0, 10, size=5))
    }
    data_df = pd.DataFrame(data)

    data_df['label_one'] = data['cloumn_one'].apply(add_val)

    print(data_df)
```

### B

```python
import pandas as pd
import numpy as np

if __name__ == '__main__':
    data = {
        'cloumn_one': pd.Series(np.random.randint(-10, 10, size=5)),
        'cloumn_two': pd.Series(np.random.randint(0, 10, size=5)),
        'cloumn_three': pd.Series(np.random.randint(0, 10, size=5))
    }
    data_df = pd.DataFrame(data)

    data_df['label_one'] = data['cloumn_one'].apply(lambda num: 1 if num>0 else 0)

    print(data_df)
```

### C

```python
import pandas as pd
import numpy as np

if __name__ == '__main__':
    data = {
        'cloumn_one': pd.Series(np.random.randint(-10, 10, size=5)),
        'cloumn_two': pd.Series(np.random.randint(0, 10, size=5)),
        'cloumn_three': pd.Series(np.random.randint(0, 10, size=5))
    }
    data_df = pd.DataFrame(data)

    def add_val(num):
        return 1 if num>0 else 0

    data_df['label_one'] = data['cloumn_one'].apply(add_val)

    print(data_df)
```