嗨,我想在if-elif语句中创建一些新的pandas数据框列。
但是,当我运行代码时,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语句,该语句有效,只是不创建熊猫列。
data = 30
if data > 20:
message = "yep"
elif data <= 20:
message = "nope"
print(message)
欢呼
答案 0 :(得分:5)
您的代码对我有用。
我刚刚使用随机整数生成了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
答案 1 :(得分:1)
使用df.assign而不是赋值,因为您的问题暗示列cal_year不会退出
替换
if data == '12 months':
df['calc_year'] = df['quarter'] * 4
elif data == '3 months':
df['calc_quarter'] = df['year'] / 4
使用
if data == '12 months':
df = df.assign(calc_year = df['quarter'] * 4)
elif data == '3 months':
df = df.assign(calc_quarter = df['year'] / 4)