英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论