Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.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如何在数据帧中将列表名用作列名_Python_Dataframe - Fatal编程技术网

Python如何在数据帧中将列表名用作列名

Python如何在数据帧中将列表名用作列名,python,dataframe,Python,Dataframe,我有一个变量列表。我想将此列表的名称分配给dataframe中的一列。名称stress及其元素不断变化 stress = ['M13', 'M14', 'M15', 'M16', 'M17', 'M18'] outputlist = [ 13, 14, 15, 16, 17 18 ] ### obtained from analysis resultdf[stress] = outputlist ### I want to name the column same as list name

我有一个变量列表。我想将此列表的名称分配给dataframe中的一列。名称
stress
及其元素不断变化

stress = ['M13', 'M14', 'M15', 'M16', 'M17', 'M18']

outputlist = [ 13, 14, 15, 16, 17 18 ]  ### obtained from analysis

resultdf[stress] = outputlist ### I want to name the column same as list name.
我想要下面给出的类似的东西

print(resultdf)
    stress
0    13
1    14
2    15
3    16
4    17
5    18

当我尝试这样做时,它会导致错误,因为整个列表值在列标题中获取列表。如何做到这一点

这可能就是您想要的,尽管我不确定结果数据是什么样的:

>>> stress = ['M13', 'M14', 'M15', 'M16', 'M17', 'M18']
>>> data = [[1,2,3,4,5,6], [7,8,9,10,11,12], [13,14,15,16,17,18], [19,20,21,22,23,24], [25,26,27,28,29,30], [31,32,33,34,35,36]]
>>> result = {x: y for x,y in zip(stress, data)}
>>> result
{'M13': [1, 2, 3, 4, 5, 6], 'M14': [7, 8, 9, 10, 11, 12], 'M15': [13, 14, 15, 16, 17, 18], 'M16': [19, 20, 21, 22, 23, 24], 'M17': [25, 26, 27, 28, 29, 30], 'M18': [31, 32, 33, 34, 35, 36]}
然后,您可以将字典转换为数据帧:

>>> import pandas as pd
>>> d = pd.DataFrame(result)
>>> d
   M13  M14  M15  M16  M17  M18
0    1    7   13   19   25   31
1    2    8   14   20   26   32
2    3    9   15   21   27   33
3    4   10   16   22   28   34
4    5   11   17   23   29   35
5    6   12   18   24   30   36
编辑(基于您的更新) 如果您只需要一列变量作为名称,请将其加引号:

>>> d = pd.DataFrame({'stress': outputlist})
>>> d
   stress
0      13
1      14
2      15
3      16
4      17
5      18

只是需要一根绳子。您正在尝试使用变量作为列名。而是写

resultd["stress"] = outputlist

这可能就是你想要做的:不。我更新了我的问题。对不起,错误的链接。你能提供一个示例
outputlist
,以及它如何映射到每个列吗?问题已更新。感谢我熟悉的这种方法。“但我不想手动操作。@Msquare那么在你的问题中,说出你真正想做的。你在含糊其辞。