[英]pandas new column with condition
我認為 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 比單行 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 = 1
: Value-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.