Python如何将列表名称用作数据框中的列名称

时间:2019-07-26 20:18:46

标签: 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.

我想要下面这样的东西。

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

当我尝试执行此操作时会导致错误,因为整个列表值都在列标题中获取列表。如何实现这一目标。

2 个答案:

答案 0 :(得分:0)

这可能是您正在寻找的,尽管我不确定结果数据是什么样的:

FROM python:3.7-slim AS compile-image
RUN apt-get update
RUN apt-get install -y --no-install-recommends build-essential gcc

RUN python -m venv /opt/venv
# Make sure we use the virtualenv:
ENV PATH="/opt/venv/bin:$PATH"

COPY requirements.txt .
RUN pip install -r requirements.txt

COPY setup.py .
COPY myapp/ .
RUN pip install .

FROM python:3.7-slim AS build-image
COPY --from=compile-image /opt/venv /opt/venv

# Make sure we use the virtualenv:
ENV PATH="/opt/venv/bin:$PATH"
CMD ['myapp']

然后您可以将字典转换为DataFrame:

>>> 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

答案 1 :(得分:0)

只需是一个字符串。您正在尝试使用变量作为列名。改写

resultd["stress"] = outputlist