Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在df中插入一组新的标头,但保留现有标头并将其设置为第一行数据_Python_Pandas_Dataframe - Fatal编程技术网

Python 在df中插入一组新的标头,但保留现有标头并将其设置为第一行数据

Python 在df中插入一组新的标头,但保留现有标头并将其设置为第一行数据,python,pandas,dataframe,Python,Pandas,Dataframe,希望修改df: Test_Data = [ ('Client', ['A','B','C']), ('2018-11', [10,20,30]), ('2018-12', [10, 20, 30]), ] df = pd.DataFrame(dict(Test_Data)) print(df) Client 2018-11 2018-12 0 A

希望修改df:

Test_Data = [
                ('Client', ['A','B','C']),
                ('2018-11', [10,20,30]),
                ('2018-12', [10, 20, 30]),
             ]

df = pd.DataFrame(dict(Test_Data))
print(df)

  Client  2018-11  2018-12
0      A       10       10
1      B       20       20
2      C       30       30
期望输出:

Report_Mongo    Client  Month_1  Month_2
0               Client  2018-11  2018-12
1               A       10       10
2               B       20       20
3               C       30       30
因此,将现有标题下移一行并插入新标题:

c = ['Report_Mongo','client', 'Month_1', 'Month_2']

我建议创建
多索引
,以避免在数据帧中混合数字字符串和数据:

c = ['Report_Mongo','client', 'Month_1', 'Month_2']

#get columns by list without first element
df.columns = [c[1:], df.columns]
#get first element to names of columns
df.columns.names = (c[0], '')
print(df)

Report_Mongo client Month_1 Month_2
             Client 2018-11 2018-12
0                 A      10      10
1                 B      20      20
2                 C      30      30
如果需要逐列第一行,可以使用
append
,但最好是第一种解决方案:

c = ['Report_Mongo','client', 'Month_1', 'Month_2']

df = df.columns.to_frame().T.append(df, ignore_index=True)
df.columns = c[1:]
df.columns.name = c[0]
print(df)

Report_Mongo  client  Month_1  Month_2
0             Client  2018-11  2018-12
1                  A       10       10
2                  B       20       20
3                  C       30       30

类似于?Hi@cs95,需要按列第一行,而不是multiindextanks@jezrael。Wierd请求,但它符合一些疯狂的Django遗留代码。