重复每列的值两次,将它们放在一起。

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

Repeat the values of each column twice and put them beside each other

问题

我有一个数据框(df),我想要将每一列的值重复2次。以下是一个示例:

  1. data = {
  2. 'id': [1],
  3. 'v_1': [103],
  4. 'v_2': [105],
  5. 'v_3': [102],
  6. }
  7. df = pd.DataFrame(data)

以下是我想要的输出(列名不重要):

  1. id v_1 v_11 v_2 v_22 v_3 v_31
  2. 0 1 103 103 105 105 102 102

你可以帮我吗?谢谢!

英文:

I have a df and I want to repeat the values of each olumn 2 times. Here is an example:

  1. data = {
  2. 'id': [1],
  3. 'v_1': [103],
  4. 'v_2': [105],
  5. 'v_3': [102],
  6. }
  7. df = pd.DataFrame(data)

and here is the output I want (the name of the columns are not important)

  1. id v_1 v_11 v_2 v_22 v_3 v_31
  2. 1 103 103 105 105 102 102

Can you please help me with this? Thank you

答案1

得分: 1

这个选项:

  1. import pandas as pd
  2. data = {
  3. 'id': [1],
  4. 'v_1': [103],
  5. 'v_2': [105],
  6. 'v_3': [102],
  7. }
  8. df = pd.DataFrame(data)
  9. for col in df.columns:
  10. df[f"{col}"+"1"] = df[col]
  11. df.columns = sorted(df.columns)
  12. print(df)
  13. id v_1 v_2 v_3 id1 v_11 v_21 v_31
  14. 0 1 103 105 102 1 103 105 102
英文:

This option:

  1. import pandas as pd
  2. data = {
  3. 'id': [1],
  4. 'v_1': [103],
  5. 'v_2': [105],
  6. 'v_3': [102],
  7. }
  8. df = pd.DataFrame(data)
  9. for col in df.columns:
  10. df[f"{col}"+"1"] = df[col]
  11. df.columns = sorted(df.columns)
  12. print(df)
  13. id v_1 v_2 v_3 id1 v_11 v_21 v_31
  14. 0 1 103 105 102 1 103 105 102

答案2

得分: 1

假设列名不重要,我们可以使用 index.repeat

  1. df.reindex(columns=['id', *df.columns.drop('id').repeat(2)])

  1. id v_1 v_1 v_2 v_2 v_3 v_3
  2. 0 1 103 103 105 105 102 102
英文:

Assuming column names are not important, we can use index.repeat

  1. df.reindex(columns=['id', *df.columns.drop('id').repeat(2)])

  1. id v_1 v_1 v_2 v_2 v_3 v_3
  2. 0 1 103 103 105 105 102 102

答案3

得分: 0

我只能翻译代码部分:

  1. list=['id']
  2. for i in df.columns[1:] :
  3. list.append(i)
  4. list.append(i+"_"+i[-1:3])
  5. list
  6. df2=pd.DataFrame(columns=list)
  7. df2

这段代码用来创建一个空的数据框(dataframe)。

英文:

I have only managed to create the empty dataframe using the following code

  1. list=['id']
  2. for i in df.columns[1:] :
  3. list.append(i)
  4. list.append(i+"_"+i[-1:3])
  5. list
  6. df2=pd.DataFrame(columns=list)
  7. df2

Sorry it's my first post here.
This gives the following dataframe

  1. id v_1 v_1_1 v_2 v_2_2 v_3 v_3_3

huangapple
  • 本文由 发表于 2023年8月4日 01:39:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76830424.html
匿名

发表评论

匿名网友

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

确定