如何将列添加到数据帧并分配条件值



我有一个简单的数据帧,我想在其中添加一个新列(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
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

试试这个


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

最新更新