python - 如何根据用户在运行时选择的逻辑创建新的 pandas 列
问题描述
我希望能够根据用户选择的公式在数据框中创建一个新列。当在运行之前知道公式选择时,答案是显而易见的,但我不确定在直到运行时才知道公式的情况下如何进行。
数据框中的列数可能会有所不同,每个公式的变量/操作数也可能会有所不同,因此 lambda 函数似乎不合适
前任。df
在“A”列中具有整数值,在“B”列中具有浮点值。有3个公式,
1
- 将 A 中的值添加到 B 中的值2
- 从 A 中的值的平方中减去 B 中的值3
- 将 A 中的值添加到 B 中的值
用户输入1
,2
或3
在运行时,相应的公式用于创建具有适当值的列“C”。
解决方案
def get_formula(user_input):
formula = None
if user_input == 1:
formula = lambda x: x['A'] + x['B']
elif user_input == 2:
formula = lambda x: x['A']**2 - x['B']
elif user_input == 3:
# Your conditions for user inputs 1 or 3 seem to be the same.
formula = lambda x: x['A'] + x['B']
else:
# Error out
pass
return formula
df = pd.DataFrame({'A': list(range(5)), 'B': list(range(5))})
# Get user input (assumes it's an integer)
user_input = int(input('Enter formula #: '))
# Get formula based on input
fn = get_formula(user_input)
# Assign new column 'C' based on formula
df.assign(C=fn)
# Assuming user input is 1, this outputs:
A B C
0 0 0 0
1 1 1 2
2 2 2 4
3 3 3 6
4 4 4 8
您可以将DataFrame.assign与运行时确定的公式一起使用。这利用了 Python 中作为对象的函数。
推荐阅读
- python - 使用python将jpg转换为pdf时旋转无效
- flutter - ListView 相当于 Flutter 中 Column 的 mainAxisSize
- ios - 如何基于其他 .p12 证书创建 IPA
- python-3.x - 使用 Cloud Functions 将文件从 Google Cloud Storage 传输到 Windows VM 实例
- graph - 将 Graphviz 节点并排放置,不带箭头
- scala - 由 spark-shell (scala) 暂存的 SparkSession 变量是 val 还是 var?
- python - 熊猫:按一天中的时间对数据框进行分组并在一个图形上绘制图
- typescript - 结构类型解决方法不起作用
- google-apps-script - 如何在 Google 表单问题帮助文本中插入换行符和超链接?
- json - AMBARI + 如何在 json REST API 中设置值