【问题标题】:How can I apply a If-function to a Dataframe如何将 If 函数应用于数据框
【发布时间】:2023-03-09 00:21:01
【问题描述】:

我对 Pandas 很陌生,我一直在尝试构建一个 if 语句函数以应用于数据框列。

我需要一个函数来查找“流入类型”列中的每一行,然后根据字母的类型在名为“现金流”的新列上分配正数或负数。

df = {'type of inflow':['I', 'D', 'I', 'D', 'R', 'D'], 'historic value':[100, 300, 200, 700, 400, 600]}

 def cash_flow(row):

     if row['type of inflow'] == "I" or row['type of inflow'] == "D":

        row['type of inflow'] = row['historic value'] * -1

     elif row['type of inflow'] == "R":

        row['cash flow'] = row['historic value'] * 1

提前致谢

【问题讨论】:

标签: python pandas dataframe


【解决方案1】:

可以使用Pandas Apply Function

import pandas as pd

# Define dataframe
df = pd.DataFrame({'type of inflow':['I', 'D', 'I', 'D', 'R', 'D'], 'historic value':[100, 300, 200, 700, 400, 600]})

def cash_flow(row):
  " Change function to return desired value based upon columns "
  if row['type of inflow'] == "I" or row['type of inflow'] == "D":
    return row['historic value'] * -1

  elif row['type of inflow'] == "R":
    return row['historic value'] * 1

# use Appy to generate cash flow colum using the cash_flow function
df['cash flow'] = df.apply(lambda row: cash_flow(row), axis = 1)
print(df)

输出

 type of inflow  historic value  cash flow
0              I             100       -100
1              D             300       -300
2              I             200       -200
3              D             700       -700
4              R             400        400
5              D             600       -600

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-03
    • 1970-01-01
    • 2020-03-29
    • 2020-09-04
    • 2019-04-24
    • 2019-06-18
    • 1970-01-01
    相关资源
    最近更新 更多