嗨,我想在if-elif语句中创建一些新的pandas dataframe列。
但是,当我运行代码时,if-elif语句不会创建任何列。
当我将代码移到if-elif语句之外时,pandas使用我使用的语法创建列。
我需要做什么才能让熊猫在if-elif语句中创建新列?
data = '3 months'
if data == '12 months':
df['calc_year'] = df['quarter'] * 4
elif data == '3 months':
df['calc_quarter'] = df['year'] / 4
我测试了我的if-elif语句,该语句有效,只是不创建pandas列。
data = 30
if data > 20:
message = "yep"
elif data <= 20:
message = "nope"
print(message)
干杯
您的代码对我有用。
我只是用随机整数生成了quarter
&year
列,并使用了您的条件,它给了我正确的输出
import pandas as pd
import numpy as np
df = pd.DataFrame()
df['quarter'] = np.random.randint(1, 6, 10)
df['year'] = np.random.randint(1, 6, 10)
data = '3 months'
if data == '12 months':
df['calc_year'] = df['quarter'] * 4
elif data == '3 months':
df['calc_quarter'] = df['year'] / 4
df
# output
df
Out[8]:
quarter year calc_quarter
0 1 5 1.25
1 3 2 0.50
2 4 5 1.25
3 1 5 1.25
4 1 3 0.75
5 5 4 1.00
6 1 2 0.50
7 4 4 1.00
8 4 4 1.00
9 1 3 0.75
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句