创建一个向量(将多列合并成一个新列)pandas。

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

create a vector (multiple columns in one new column) pandas

问题

You can achieve the desired result by creating a new DataFrame with a multi-level column index. Here's how you can do it:

import pandas as pd

data = {
    "a": [420, 380, 390],
    "b": [50, 40, 45],
    "c": [30, 22, 11],
    "d": [323, 2, 33]
}

df = pd.DataFrame(data)

# Create a new DataFrame with multi-level columns
new_columns = pd.MultiIndex.from_tuples([("a", ""), ("b", "c"), ("d", "")])
result_df = pd.DataFrame(df, columns=new_columns)

print(result_df)

This code will give you the desired result:

     a    d
        b   c    d
0  420  50  30  323
1  380  40  22    2
2  390  45  11   33

It creates a new DataFrame result_df with the desired column structure.

英文:

Please, i have a dataframe like this:

data = {
    "a": [420, 380, 390],
    "b": [50, 40, 45],
    "c": [30, 22, 11],
    "d": [323, 2, 33]
}

df = pd.DataFrame(data)
a   b   c    d
0  420  50  30  323
1  380  40  22    2
2  390  45  11   33

and i want to get this result:

    a   d
        b   c    d
0  420  50  30  323
1  380  40  22    2
2  390  45  11   33

do you have any suggestions ?

i tried merge and concatenate but not working for me

答案1

得分: 1

尝试使用pd.MultiIndex:

df.columns = pd.MultiIndex.from_arrays([['a', 'd'], ['b', 'c', 'd']])

输出:

     a    d         
     b    c    d
0  420  50  30  323
1  380  40  22    2
2  390  45  11   33
英文:

Try this using pd.MultiIndex:

df.columns = pd.MultiIndex.from_arrays([[*'addd'],[*' bcd']])

Output:

     a   d         
         b   c    d
0  420  50  30  323
1  380  40  22    2
2  390  45  11   33

huangapple
  • 本文由 发表于 2023年5月17日 21:33:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76272702.html
匿名

发表评论

匿名网友

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

确定