![](/img/trans.png)
[英]Creating new column based on if statement of another column grabbing data from yet two different columns
[英]IF Statement - Creating New Column Based on Two Columns
我想創建一個包含過去值的新列df2.past_values
和未來值df2.future_value
稱為df2['past_future_mix']
如果 window = 0,這些是過去的值,window = 1,這些是未來的值
我正在嘗試使用 if elif 語句,但是我收到此錯誤:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
import pandas as pd
import numpy as np
from datetime import timedelta
# Set up input data (taken from original post)
df1 = pd.DataFrame({
'past_value': [100, 200, 200, 300, 350, 400, 'NaN', 'NaN', 'NaN', 'NaN', 'NaN', 'NaN'],
'future_value': ['NaN', 'NaN', 'NaN', 'NaN', 'NaN', 'NaN', 800, 900, 900, 950, 975, 1000],
'window': [0,0,0,0,0,0,1,1,1,1,1,1],
'category': ['Category A']*4 + ['Category B']*4 + ['Category C']*4})
ca_list = df1.category.unique()
bigdf = pd.DataFrame()
for cat in cat_list:
df2 = df1[(df1.category == cat)]
if df2['window'] == 0:
df2['past_future_mix'] = df2['past_value']
elif df2['window'] == 1:
df2['past_future_mix'] = df2['future_value']
bigdf = bigdf.append(df2)
這是我收到的錯誤消息:
ValueError Traceback (most recent call last)
<ipython-input-56-cfdd200ce9ff> in <module>
16 for cat in cat_list:
17 df2 = df1[(df1.category == cat)]
---> 18 if df2['window'] == 0:
19 df2['past_future_mix'] = df2['past_value']
20 elif df2['window'] == 1:
~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\generic.py in __nonzero__(self)
1553 "The truth value of a {0} is ambiguous. "
1554 "Use a.empty, a.bool(), a.item(), a.any() or a.all().".format(
-> 1555 self.__class__.__name__
1556 )
1557 )
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
我將if df2['window] == 0
更改為if 0 in df2['window']
,但是它現在不打印數據幀。
for cat in cat_list:
df2 = df1[(df1.category == cat)]
if 0 in df2['window']:
df2['past_future_mix'] = df2['past_value']
elif 1 in df2['window']:
df2['past_future_mix'] = df2['future_value']
bigdf = bigdf.append(df2)
print(bigdf)
你可以試試.loc
for cat in cat_list:
df2 = df1[(df1.category == cat)]
df2.loc[df2['window'] == 0, 'past_future_mix'] = df2['past_value']
df2.loc[df2['window'] == 1, 'past_future_mix'] = df2['future_value']
bigdf = bigdf.append(df2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.