rav*_*ana 0 python if-statement conditional-statements
我试图弄清楚是否有更好的方法来根据条件对数据进行分类。
示例数据: 查看已识别的地点是否具有物理、社会和/或经济角色。如果存在任何/多个角色,则该位置标记为“1”。
import pandas as pd
df = pd.DataFrame([[0, 1, 0], [0, 1, 1], [0, 1, 0], [0, 0, 1], [1,1,1], [1,1,0], columns=["PHYSICAL", "SOCIAL", "ECONOMIC"])
Run Code Online (Sandbox Code Playgroud)
数据
| | PHYSICAL | SOCIAL | ECONOMIC |
| - | -------- | ------ | -------- |
| 0 | 0 | 1 | 0 |
| 1 | 0 | 1 | 1 |
| 2 | 0 | 1 | 0 |
| 3 | 0 | 0 | 1 |
| 4 | 1 | 1 | 1 |
| 5 | 1 | 1 | 0 |
Run Code Online (Sandbox Code Playgroud)
我想知道的:如何创建一个新列,根据 True/False 值为每一行分配一个类别。
所有可能的类别:
预期成绩
| | PHYSICAL | SOCIAL | ECONOMIC | CATEGORY |
| - | -------- | ------ | -------- | --------------- |
| 0 | 0 | 1 | 0 | social |
| 1 | 0 | 1 | 1 | social_economic |
| 2 | 0 | 1 | 0 | social |
| 3 | 0 | 0 | 1 | economic |
| 4 | 1 | 1 | 1 | all_cat |
| 5 | 1 | 1 | 0 | physical_social |
Run Code Online (Sandbox Code Playgroud)
我试过的:
df['CATEGORY'] = np.where(df['PHYSICAL'], np.where(df['SOCIAL'],
np.where(df['ECONOMIC'], 'All', 'FALSE'), 'FALSE'), 'FALSE')
Run Code Online (Sandbox Code Playgroud)
谢谢!
您可以使用df.dot为
df['CATEGORY'] = df.dot(df.columns + '_').str.rstrip('_').str.lower()
Run Code Online (Sandbox Code Playgroud)
输出:
PHYSICAL SOCIAL ECONOMIC CATEGORY
0 0 1 0 social
1 0 1 1 social_economic
2 0 1 0 social
3 0 0 1 economic
4 1 1 1 physical_social_economic
5 1 1 0 physical_social
Run Code Online (Sandbox Code Playgroud)