pandas 如何覆盖数据框中的多个列,并根据其他多个列中的信息分配新的列值[重复]

6qqygrtg  于 2023-11-15  发布在  其他
关注(0)|答案(1)|浏览(99)

此问题在此处已有答案

How do I create a new column where the values are selected based on existing columns?(13个回答)
17天前关闭。
新手在这里..但非常热情.我有很多的调查数据,我必须在一个新创建的列中派生一个值在一个基于0或1的多个其他列的嵌套框.

  1. dftest = pd.DataFrame({'connection_0': ['0', '1','0','0','1'], 'connection_1': ['1', '0','1','1','0']},index=['819', '820','821','822','823'])

字符串
所以它是这样的:

  1. connection_0 connection_1
  2. 819 0 1
  3. 820 1 0
  4. 821 0 1
  5. 822 0 1
  6. 823 1 0


我想在前面添加一个列“connect”,如果connection_0是“1”,则将该列的值设置为“none”,如果connection_1是"1",则将该列的值设置为“patient”。实际上,我有两个以上的列(connection_2等),但我可以稍后处理。我还有数千行数据,因此这只是一个测试 Dataframe 。
我想要的是-

  1. connect connection_0 connection_1
  2. 819 patient 0 1
  3. 820 none 1 0
  4. 821 patient 0 1
  5. 822 patient 0 1
  6. 823 none 1 0


这是我的尝试,有点工作,但它设置所有'连接'到'无'
对于索引,dftest.iterrows()中的行:

  1. if row[0]=="1": row.connect=row.connect.replace('1', 'none')
  2. else:
  3. if row[0]=="0" & row[1]=="1":row.connect=row.connect.replace('1', 'patient')


但我明白了

  1. connect connection_0 connection_1
  2. 819 none 0 1
  3. 820 none 1 0
  4. 821 none 0 1
  5. 822 none 0 1
  6. 823 none 1 0


我知道我在做一些非常愚蠢的事情,所以任何帮助都将不胜感激!!

uqdfh47h

uqdfh47h1#

验证码

如果你需要在其他列中添加类似的操作,而不是两列,似乎使用np.select是最好的方法。你可以通过添加cond#来增加要应用的列数。

  1. import numpy as np
  2. cond1 = dftest['connection_0'].eq('1')
  3. cond2 = dftest['connection_1'].eq('1')
  4. arr = np.select([cond1, cond2], ['none', 'patient'])
  5. out = pd.DataFrame(arr, columns=['connect'], index=dftest.index).join(dftest)

字符串
输出:

  1. connect connection_0 connection_1
  2. 819 patient 0 1
  3. 820 none 1 0
  4. 821 patient 0 1
  5. 822 patient 0 1
  6. 823 none 1 0


让它更简洁:

  1. import numpy as np
  2. arr = np.select(dftest.eq('1').T.values, ['none', 'patient'])
  3. out = pd.DataFrame(arr, columns=['connect'], index=dftest.index).join(dftest)


如果所有列都包含“1”,也可以按以下方式执行。
让我们创建一个字典,它为每一列分配'1'时要分配的值,并将其分配给m

  1. m = {'connection_0':'none', 'connection_1':'patient'}
  2. dftest.eq('1').idxmax(axis=1).map(m).to_frame('connect').join(dftest)

展开查看全部

相关问题