簡體   English   中英

pandas 有條件的新列

[英]pandas new column with condition

我有一個數據框如下:

數據

我需要創建一個新列,名稱為 Value-2:如果 value-1 小於 500,則需要用 0.5 填充該值。 如果該值小於1000,則需要用1填充該值。

預期結果:

輸出

有人能幫我嗎?

我認為 np.where function 也能有效處理海量數據。

import pandas as pd
import numpy as np

dictionary = {
    "Company" : ['A','A','A','A','A','A'],
    "Value1" : [480,120,876,340,996,1104]
}

dataframe = pd.DataFrame(dictionary)
dataframe["Value2"] = np.where(dataframe["Value1"] < 500, 1, 0.5)

Output:

  Company  Value1  Value2
0       A     480     0.5
1       A     120     0.5
2       A     876     1.0
3       A     340     0.5
4       A     996     1.0
5       A    1104     1.0

試試這個你可以根據你的需要調整算法。 這是一個簡單的if / else

df['Value-2'] = df['Value-1'].apply(lambda x: 0.5 if x < 500 else 1)

#  Company  Value-1  Value-2
# 0       A      480      0.5
# 1       A      120      0.5
# 2       A      876      1.0
# 3       A      340      0.5
# 4       A      996      1.0
# 5       A     1104      1.0

使用自定義 function

這里要求的是如何編寫自定義 function 比單行 lambda function 具有更大的靈活性。

def my_fun(x):
  # can be a switch case or any complex algorithm
  return 0.5 if x < 500 else 1

df['Value-2'] = df['Value-1'].apply(my_fun)

筆記

這個問題在一點上並不一致。 它說

如果值小於 1000,需要用 1 填充值。

但是對於高於 1000 的“Value-1”,預期結果顯示Value-2 = 1Value-1 = 1104

請日后提問時提供工作代碼。

import pandas as pd

Data = {
    "Company" : ['A','A','A','A','A','A'],
    "Value1" : [480,120,876,340,996,1104]
}

DataFrame1 = pd.DataFrame(Data)

DataFrame2 = []

for x in DataFrame1['Value1']:
    if x < 500 : DataFrame2.append(0.5)
    elif x < 1000 or x > 1000 : DataFrame2.append(1) # As the picture given in the question tells Value 2 is 1 when value 1 is 1104
    else : pass

DataFrame1['Value2'] = DataFrame2
print(DataFrame1)
Outputs
  Company  Value1  Value2
0       A     480     0.5
1       A     120     0.5
2       A     876     1.0
3       A     340     0.5
4       A     996     1.0
5       A    1104     1.0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM