dataframe.at[]添加新列,而不是添加值

2024-09-30 14:17:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧:

  APPLICATION     COUNT K3_Code_Sender K3_Code_Receiver TWO
0    BCCTBL_2       0.0              0              287   x
1    BDLSMF01       0.0           9996                0   x
2    BEX00003       0.0            762                0   x
3    BEX01910  711762.0            762                0   x
4    BEX02955      60.0              0              287   x
5    BEX02970   12058.0            762              387   x
6    BEX03148     179.0              0                0   x

在下面的iterate和if语句(行[4]=行['TWO']之后,这样做只是为了检查列位置)

    for index, row in df_fin_k.iterrows():
        if row['K3_Code_Sender'] != '0' and row['K3_Code_Receiver'] != '0':
            df_fin_k.at[index, row[4]] = 2
        else:
            df_fin_k.at[index, row['TWO']] = 1

我获取新列,而不是将值设置为两列:

  APPLICATION     COUNT K3_Code_Sender K3_Code_Receiver TWO    x
0    BCCTBL_2       0.0              0              287   x  1.0
1    BDLSMF01       0.0           9996                0   x  1.0
2    BEX00003       0.0            762                0   x  1.0
3    BEX01910  711762.0            762                0   x  1.0
4    BEX02955      60.0              0              287   x  1.0
5    BEX02970   12058.0            762              387   x  2.0
6    BEX03148     179.0              0                0   x  1.0

如何解决此问题,以便我们能够:

  APPLICATION     COUNT K3_Code_Sender K3_Code_Receiver TWO
0    BCCTBL_2       0.0              0              287   1.0
1    BDLSMF01       0.0           9996                0   1.0
2    BEX00003       0.0            762                0   1.0
3    BEX01910  711762.0            762                0   1.0
4    BEX02955      60.0              0              287   1.0
5    BEX02970   12058.0            762              387   2.0
6    BEX03148     179.0              0                0   1.0

Tags: applicationcountcodesenderrowreceivertwok3
2条回答

试试这个

for index, row in df_fin_k.iterrows():
    if row['K3_Code_Sender'] != '0' and row['K3_Code_Receiver'] != '0':
        df_fin_k.at[index, 'TWO'] = 2
    else:
        df_fin_k.at[index, 'TWO'] = 1

我已将df_fin_k.at[index, row['TWO']] = 1替换为df_fin_k.at[index, 'TWO'] = 1

我试过这个:

for index , row in df.iterrows():
  if row['K3_Code_Sender'] + row['K3_Code_Receiver'] == 0:
    df['TWO'][index] = 2
  else: 
    df['TWO'][index] = 1

相关问题 更多 >

    热门问题