[英]pandas if-elif statement not creating new dataframe columns
嗨,我想在 if-elif 语句中创建一些新的 pandas dataframe 列。
但是,当我运行代码时,if-elif 语句没有创建任何列。
当我将代码放在 if-elif 语句之外时,pandas 使用我正在使用的语法创建列。
我需要做什么才能让 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
列,并使用了你的条件,它给了我正确的 output
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
使用 df.assign 而不是分配,因为您的问题暗示 colum 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.