Как умножить между столбцами разных строк в Python - PullRequest
0 голосов
/ 15 февраля 2019

Вот уравнение.Пример

Numbers     | Date      | Mean
1000        |12/1/2018  | 1
1002        |12/2/2018  | 0
1003        |12/3/2018  | 0.5
 0          |12/4/2018  | 0.6
 0          |12/5/2018  | 0.4
 0          |12/6/2018  |0.1
 0          |12/7/2018  | -0.7
 0          |12/8/2018  | 0.2
 0          |12/9/2018  | -0.1

Вот что я хочу

|Numbers | Date      | Mean | Multiplication |
| ------ |-----------|------|----------------|
|1000    | 12/1/2018 | 1    | 1000           |
|1002    | 12/2/2018 | 0    | 0*1000= 0      |
|1003    | 12/3/2018 | 0.5  | 0.5*1002=501   |
|0       | 12/4/2018 | 0.6  | 1003*0.6=601.8 |
|0       | 12/5/208  | 0.4  | 601.8*0.4
|0       | 12/6/2018 | 0.1  | 601.8*0.4*0.1  |
|0       |12/7/2018  | -0.7 |601.8*0.4*0.1*-0.7| 
 0       |12/8/2018  | 0.2  |601.8*0.4*0.1*-0.7*0.2
 0       |12/9/2018  | -0.1 |601.8*0.4*0.1*-0.7*0.2*-0.1

данные уже находятся во фрейме данных, и я использую функции панд

Ответы [ 2 ]

0 голосов
/ 15 февраля 2019

@ Даниэль Лаббе ответил за начальные требования, и это было правильно.+1 ему за метод shift ().Затем требования пользователей изменились.Итак, вот мой ответ на последние требования.

#import pandas for managing data with dataframe
import pandas as pd
#import tabulate to print your data frame as table
from tabulate import tabulate
#Create a data dictionary
myData={'Numbers':[1000,1002,1003,0,0,0,0,0,0],'Date':['12/1/2018','12/2/2018','12/3/2018','12/4/2018','12/5/2018','12/6/2018','12/7/2018','12/8/2018','12/9/2018'],'Mean':[1,0,0.5,0.6,0.4,0.1,-0.7,0.2,-0.1]}
#Create a data frame from the data dictionary using pandas. User mentioned that the data is already in the
#pandas data frame
myDataFrame=pd.DataFrame(myData)
#Print your final table (just pretty print)
print(tabulate(myDataFrame, headers='keys', tablefmt='psql'))
#Declare a list
MultiplicationList=[]
#Declare a constant
StorePreviousValue=0
for i in range(0,len(myDataFrame['Numbers'])):
    #If it is the first row then use the Number
    if i==0:
        #Append the value to the list
        MultiplicationList.append(myDataFrame['Numbers'][i])
    else:
        #If it is not the first row, and the value in the first column of the previous row is '0'
        #multiply Mean with the previous multiplication result
        if myDataFrame['Numbers'][i-1]==0:
            StorePreviousValue=StorePreviousValue*myDataFrame['Mean'][i]
        #If it is not the first row, and the value in the first column of the previous row is not '0'
        #(should probably say greate than '0', but the question is not clear about that), then 
        #multiply Mean with the Number in the first column of the previous row
        else:
            StorePreviousValue=myDataFrame['Numbers'][i-1]*myDataFrame['Mean'][i]
        #Append the value to the list
        MultiplicationList.append(StorePreviousValue)
#Create a new column in the data frame and pass the list as the value
myDataFrame['Multiplication']=MultiplicationList
#Print your final table (just pretty print)
print(tabulate(myDataFrame, headers='keys', tablefmt='psql'))

Вот вывод

+----+-----------+-----------+--------+
|    |   Numbers | Date      |   Mean |
|----+-----------+-----------+--------|
|  0 |      1000 | 12/1/2018 |    1   |
|  1 |      1002 | 12/2/2018 |    0   |
|  2 |      1003 | 12/3/2018 |    0.5 |
|  3 |         0 | 12/4/2018 |    0.6 |
|  4 |         0 | 12/5/2018 |    0.4 |
|  5 |         0 | 12/6/2018 |    0.1 |
|  6 |         0 | 12/7/2018 |   -0.7 |
|  7 |         0 | 12/8/2018 |    0.2 |
|  8 |         0 | 12/9/2018 |   -0.1 |
+----+-----------+-----------+--------+
+----+-----------+-----------+--------+------------------+
|    |   Numbers | Date      |   Mean |   Multiplication |
|----+-----------+-----------+--------+------------------|
|  0 |      1000 | 12/1/2018 |    1   |      1000        |
|  1 |      1002 | 12/2/2018 |    0   |         0        |
|  2 |      1003 | 12/3/2018 |    0.5 |       501        |
|  3 |         0 | 12/4/2018 |    0.6 |       601.8      |
|  4 |         0 | 12/5/2018 |    0.4 |       240.72     |
|  5 |         0 | 12/6/2018 |    0.1 |        24.072    |
|  6 |         0 | 12/7/2018 |   -0.7 |       -16.8504   |
|  7 |         0 | 12/8/2018 |    0.2 |        -3.37008  |
|  8 |         0 | 12/9/2018 |   -0.1 |         0.337008 |
+----+-----------+-----------+--------+------------------+

Если у вас нет панд или таблиц, пожалуйста, установите с помощью pip install pandas pipinstall tabulate

Если вы не знакомы с pip, поищите его в Google.Этот ответ предполагает, что вы знаете, как читать из файла и создавать свой словарь данных.Если вы этого не сделаете, это будет еще один вопрос.

0 голосов
/ 15 февраля 2019

Если вы используете фрейм данных Pandas, вы можете использовать метод shift () :

df['Multiplication'] = df.Mean * df.Numbers.shift(1)
df.loc[0, 'Multiplication'] = df.Numbers[0]
for i in range(len(df[df.Numbers.shift(1) == 0])):
    df.loc[df[df.Numbers.shift(1) == 0].index, 'Multiplication'] = df[df.Numbers.shift(1) == 0].Mean.values * df[df.index.isin(df[df.Numbers.shift(1) == 0].index-1)].Multiplication.values

со следующим выводом:

enter image description here

В первой строке вы не должны умножать оба числа, поэтому после умножения производится обновление значения.

Теперь выполняется требование нулевых числовых значений.

Немного разбить код, как @ Raj006 предлагает:

# return just the rows that match the condition (Numbers column 0 for the row before)
df[df.Numbers.shift(1) == 0].index

# update the values for the column Multiplication with the matching rows
df.loc[df[df.Numbers.shift(1) == 0].index, 'Multiplication']

# the value to be update is the [Mean value for the matching rows] * [rows before the matching Multiplication value]
df[df.Numbers.shift(1) == 0].Mean.values * df[df.index.isin(df[df.Numbers.shift(1) == 0].index-1)].Multiplication.values

Редактировать: мне пришлось использовать цикл for, к сожалению, для запуска столько раз, сколько совпадающих строк, как толькорасчет зависит от расчета до.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...