如何在数据框中添加一列并分配条件值?

时间:2019-06-03 03:12:16

标签: python-3.x pandas

我有一个简单的数据框,我想在其中添加一个新列(col3),其值由'col1'中的值确定。如果'col1'中的值以A开头,我想将'A'放入col3中。和以B开头的值类似。

import pandas as pd

d = {"col1" : ["A1", "A2", "B1", "B2"], "col2" : [1, 2, 3, 4]}
df = pd.DataFrame(data = d)
df

2 个答案:

答案 0 :(得分:0)

import numpy as np
import pandas as pd
d = {"col1" : ["A1", "A2", "B1", "B2"], "col2" : [1, 2, 3, 4]}
df = pd.DataFrame(data = d)
df['col3']=np.where((df.col1.str.startswith('A')),'A',df.col1)
df['col3']=np.where((df.col1.str.startswith('B')),'B',df.col3)
df

输出

   col1 col2 col3
0   A1  1     A
1   A2  2     A
2   B1  3     B
3   B2  4     B

答案 1 :(得分:0)

尝试


import numpy as np
import pandas as pd

d = {"col1" : ["A1", "A2", "B1", "B2", "C1", "C2"], "col2" : [1, 2, 3, 4, 5, 6]}
df = pd.DataFrame(data = d)

df['col3']=df["col1"].str[0]
print(df)

这导致您进入

    col1  col2  col3
0   A1     1    A
1   A2     2    A
2   B1     3    B
3   B2     4    B
4   C1     5    C
5   C2     6    C