Meh*_*imi 4 python dataframe pandas
考虑这个Dataframe:
df = pd.DataFrame({'A': [1, 1, 2, 2, 3, 3],
'B': [10, 15, 20, 25, 30,35],
'C': [100, 150, 200, 250, 300, 350]},)
A B C
1 10 100
1 15 150
2 20 200
2 25 250
3 30 300
3 35 350
Run Code Online (Sandbox Code Playgroud)
我用它来获取每组第一行的C列值:
firsts = df.groupby('A').first()['C']
Run Code Online (Sandbox Code Playgroud)
首先是:(100, 200, 300).
现在我想添加新列,如果行的列C的值为"否则它将为"1,firsts否则它将为"0".
A B C D
1 10 100 1
1 15 150 0
2 20 200 1
2 25 250 0
3 30 300 1
3 35 350 0
Run Code Online (Sandbox Code Playgroud)
我用过这个:
df['D'] = df['C'].apply(lambda x: 1 if x in firsts else 0)
Run Code Online (Sandbox Code Playgroud)
但输出是:
A B C D
1 10 100 0
1 15 150 0
2 20 200 0
2 25 250 0
3 30 300 0
3 35 350 0
Run Code Online (Sandbox Code Playgroud)
如果有人解释为什么我的解决方案是错误的,以及这个问题的实际解决方案,我感谢.
你可以使用isin方法:
df['D'] = df.C.isin(firsts).astype(int)
df
# A B C D
#0 1 10 100 1
#1 1 15 150 0
#2 2 20 200 1
#3 2 25 250 0
#4 3 30 300 1
#5 3 35 350 0
Run Code Online (Sandbox Code Playgroud)
你的方法失败的原因是python in操作符检查Series的索引而不是值,与字典的工作方式相同:
firsts
#A
#1 100
#2 200
#3 300
#Name: C, dtype: int64
1 in firsts
# True
100 in firsts
# False
2 in firsts
# True
200 in firsts
# False
Run Code Online (Sandbox Code Playgroud)
修改您的方法如下:
firstSet = set(firsts)
df['C'].apply(lambda x: 1 if x in firstSet else 0)
#0 1
#1 0
#2 1
#3 0
#4 1
#5 0
#Name: C, dtype: int64
Run Code Online (Sandbox Code Playgroud)
长话短说:
df['newColumn'] = np.where((df.compareColumn.isin(yourlist)), TrueValue, FalseValue)
Run Code Online (Sandbox Code Playgroud)
另一种一步法是使用np.where()和isin。
import pandas as pd
import numpy as np
df = pd.DataFrame({'A': [1, 1, 2, 2, 3, 3],
'B': [10, 15, 20, 25, 30,35],
'C': [100, 150, 200, 250, 300, 350]})
df['D'] = np.where((df.B.isin(firsts)), 1, 0)
Run Code Online (Sandbox Code Playgroud)
我们使用 return fromisin作为条件 innp.where()来返回
1什么时候True0什么时候False并将它们分配给同一数据框中的新列df['D']。
注意:允许使用 按位np.where运算符和替换情况更复杂的条件,即“绕过”False
df['col1'] = np.where(((df['col1'] == df['col2']) &
(~df['col1'].str.startswith('r'))),
'replace', df['col1'])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14119 次 |
| 最近记录: |