【问题标题】:Python code to multiply two columns and then create new column with valuesPython代码将两列相乘,然后用值创建新列
【发布时间】:2017-02-24 16:45:15
【问题描述】:

我正在编写一个 python 代码,它首先将分钟数据平均为每小时数据。然后,我想将每小时数据中两列中的值相乘,并用相乘后的值创建一个新列。我被困在乘法步骤上。

import pandas as pd
import numpy as np

df = pd.read_csv("inputfile.csv", index_col="DateTime", parse_dates=True)
df = df.resample('1H').mean()
df = df.reindex(pd.date_range(df.index.min(), df.index.max(), freq="1H"))
df.to_csv('outputfile.csv', index=True, index_label="DateTime")

每小时平均值的数据

DateTime        current     voltage
11/1/2014 0:00  3.366184207 12.1758535
11/1/2014 1:00  3.361604775 12.1827364
11/1/2014 2:00  3.358049691 12.17596822
11/1/2014 3:00  3.354833198 12.1827364
11/1/2014 4:00  3.361096907 12.1827364
11/1/2014 5:00  3.361096907 12.1827364
11/1/2014 6:00  3.366344918 15.72258904
11/1/2014 7:00  3.419681019 1495.925115
11/1/2014 8:00  3.663316184 1870.538086
11/1/2014 9:00  4.369056237 1925.408667
11/1/2014 10:00 4.404945809 1938.888254
11/1/2014 11:00 4.711192238 1994.759897
11/1/2014 12:00 4.82263279  1995.281601
11/1/2014 13:00 4.428242773 1961.089536
11/1/2014 14:00 4.038091129 1895.686707
11/1/2014 15:00 4.04098199  1904.352924
11/1/2014 16:00 3.748518044 1852.646768
11/1/2014 17:00 3.397967499 1554.434254
11/1/2014 18:00 3.371380174 56.24243593
11/1/2014 19:00 3.375613815 12.18733199
11/1/2014 20:00 3.369686692 12.18239812
11/1/2014 21:00 3.367993271 12.18351949
11/1/2014 22:00 3.374089682 12.17048603
11/1/2014 23:00 3.367485231 12.18946266

我想将当前列乘以电压列并使用这些值创建一个新列。

【问题讨论】:

  • 你试过df['current'] * df['voltage']吗?

标签: python python-3.x pandas


【解决方案1】:

df[newcolumn] = df['current']*df['voltage']
会工作的。
您可以将提供新列命名为变量。

def getPower(df, newColumn, numOfCol):
    for i in range(numOfCol):
        current = 'current#%d' % (i+1)
        voltage = 'voltage#%d' % (i+1)
        power   = 'power#%d' % (i+1)
    df[power] = df[current]*df[voltage]

getPower(df, 'Power', numOfCols) would create the column.

编辑:如果您将当前列命名为 'current1', current2',...

,这将起作用

【讨论】:

  • 刚看到这个。您能帮我理解#%d 是什么,'current#%d' % (i+1) 步骤可以做什么吗?
  • %d (%s for string ) 用于标记您要在字符串中插入十进制值的位置。当前方法是"sometring {}".format(obj_to_insert)
【解决方案2】:

你可以试试这样的:

df['Power'] = df['current']*df['voltage']

【讨论】:

  • 这是可行的,但是无论如何都可以在不输入列标题的情况下编写它,而只需使用列号进行乘法。
  • @acb 你是什么意思?
  • 抱歉,我的实际数据有点让人困惑,目前大约有 10 列。我想将每列乘以电压并创建 10 个新的电源列。
  • @acb 你有多个名为'current'的列吗?
  • @BFurtado 只做df.loc[:, 'Power'] = ...
猜你喜欢
  • 1970-01-01
  • 2013-10-19
  • 1970-01-01
  • 1970-01-01
  • 2020-08-19
  • 2022-01-13
  • 1970-01-01
  • 2010-10-01
  • 2022-11-15
相关资源
最近更新 更多