有没有办法在Pandas的多个栏中添加标题?

时间:2019-03-29 11:58:08

标签: python pandas dataframe

我有一个像这样的数据帧Head of df

我想在第二,第三和第四列上方添加一个标题为“累计均值”的标题,以避免在每一列中都写3次。

你有什么主意吗?

3 个答案:

答案 0 :(得分:1)

我明白了你的意思,发布了一个虚假的情况:

请考虑以下数据框:

df = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]],columns=['a','cum_a','cum_b'])
print(df)
   a  cum_a  cum_b
0  1      2      3
1  4      5      6
2  7      8      9

我们的目标是更改带有模式的列,例如cum_acum_b。这可以通过使用df.filter()来完成:

values_to_rename=['change1','change2'] #sequential list of values to replace
d=dict(zip(df.filter(like='cum').columns,values_to_rename)) #create a dict
#{'cum_a': 'change1', 'cum_b': 'change2'}

df=df.rename(columns=d)
print(df)

   a  change1  change2
0  1        2        3
1  4        5        6
2  7        8        9

答案 1 :(得分:1)

您可以使用Pandas MultiIndex:https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html

例如,(示例仅从文档改编而成)

col_names = [['', 'Cumulative mean', 'Cumulative mean', 'Cumulative mean'],['error', 'days', 'hour', 'minute']]
col_tuples = list(zip(*col_names))
index = pd.MultiIndex.from_tuples(col_tuples)

# use random numbers
listsForDataframe = np.array([
    np.random.normal(size=4), #list1
    np.random.normal(size=4), #list2
    np.random.normal(size=4), #list3
    np.random.normal(size=4)  #list4
])

# create the dataframe from lists like you did from the comment
# include the multiindex object
pd.DataFrame(listsForDataframe.T,columns=index)

结果:

            Cumulative mean                    
      error            days      hour    minute
0  0.008628        0.037006 -0.805627 -1.951804
1  0.527004        0.767902 -1.118312 -0.659892
2  0.453782        0.589880 -0.131054 -1.139802
3 -1.829740       -0.363859  1.133080  0.784958

通过“累积均值”多列进行子集化后得到print(d[['Cumulative mean']])

  Cumulative mean                    
             days      hour    minute
0        0.037006 -0.805627 -1.951804
1        0.767902 -1.118312 -0.659892
2        0.589880 -0.131054 -1.139802
3       -0.363859  1.133080  0.784958

答案 2 :(得分:-1)

请尝试执行此操作

import pandas as pd
import numpy as np

df = {'col_1': [0, 1, 2, 3],
    'col_2': [4, 5, 6, 7]}
df = pd.DataFrame(df)

df[[ 'column_new_1', 'column_new_2','column_new_3']] = [np.nan, 'dogs',3]

这可能可以解决问题

或者您可以尝试使用此示例

import pandas as pd
import numpy as np

df = pd.DataFrame({
'col_1': [0, 1, 2, 3],
'col_2': [4, 5, 6, 7]
 })

这些是您可以使用的示例,但是您当然需要自己添加数据。

希望这有助于创建多行列

相关问题