在特定列中查找列名并输入其编号

huangapple go评论112阅读模式
英文:

To find a column name in a specific column and enter its number

问题

Python.
我将使用pandas。
从第1列中定位列名。
在输入列0中找到文本中的列名,并将其输入为数字。

  1. import pandas as pd
  2. data = [['EA', 0, 0, 0], ['col2,col2', 0, 0, 0], ['col3', 0, 0, 0]]
  3. df_input = pd.DataFrame(data, columns=[0, 'EA', 'col2', 'col3'])
  4. df_input
  5. data = [['EA', 1, 0, 0], ['col2,col2', 0, 2, 0], ['col3', 0, 0, 1]]
  6. df_output = pd.DataFrame(data, columns=[0, 'EA', 'col2', 'col3'])
  7. df_output
英文:

Python.
I'm going to use a pandas
Locate the column name from column 1.
Locate the column name in the text entered in column 0 and enter the number as a number.

  1. import pandas as pd
  2. data = [['EA',0,0,0], ['col2,col2', 0, 0,0], ['col3', 0,0,0]]
  3. df_input = pd.DataFrame(data, columns=[0, 'EA', 'col2', 'col3'])
  4. df_input
  5. data = [['EA',1,0,0], ['col2,col2', 0, 2,0], ['col3', 0,0,1]]
  6. df_output = pd.DataFrame(data, columns=[0, 'EA', 'col2', 'col3'])
  7. df_output

答案1

得分: 2

你可以使用 str.extractall,然后使用 crosstab 进行操作:

  1. s = (df_input[0]
  2. .str.extractall('([^,]+)')[0]
  3. .droplevel(-1)
  4. )
  5. # 在原地更新
  6. df_input.update(pd.crosstab(s.index, s))

或者创建一个新的 DataFrame:

  1. df_output = (pd.crosstab(s.index, s)
  2. .combine_first(df_input)
  3. .reindex_like(df_input)
  4. )

输出如下:

  1. 0 EA col2 col3
  2. 0 EA 1 0 0
  3. 1 col2,col2 0 2 0
  4. 2 col3 0 0 1

如果 col2,col2 变成了 col2,col3,输出如下:

  1. 0 EA col2 col3
  2. 0 EA 1 0 0
  3. 1 col2,col3 0 1 1
  4. 2 col3 0 0 1
英文:

You can use str.extractall then a crosstab:

  1. s = (df_input[0]
  2. .str.extractall('([^,]+)')[0]
  3. .droplevel(-1)
  4. )
  5. # update in place
  6. df_input.update(pd.crosstab(s.index, s))

Or for a new DataFrame:

  1. df_output = (pd.crosstab(s.index, s)
  2. .combine_first(df_input)
  3. .reindex_like(df_input)
  4. )

Output:

  1. 0 EA col2 col3
  2. 0 EA 1 0 0
  3. 1 col2,col2 0 2 0
  4. 2 col3 0 0 1

Output if col2,col2 was col2,col3:

  1. 0 EA col2 col3
  2. 0 EA 1 0 0
  3. 1 col2,col3 0 1 1
  4. 2 col3 0 0 1

huangapple
  • 本文由 发表于 2023年5月25日 10:56:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76328620.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定