python - 从 for 循环的输出创建 pandas 数据框

标签 python pandas dataframe

我有以下循环,它根据输入数据帧生成多行:

for _, value in df.iterrows():

    var1 = value['Sales']
    var2 = value['Income']

    seg1 = value['segment']

    flag1 = 'up' if var1>0 else 'down'
    flag2 = 'up' if var2>0 else 'down'

    print(f"{seg1} Sales {flag1} {var1}% vs LY while Total income {flag2} {var2}% vs LY creating leverage")

输出

A Sales up 184.37% vs LY while Total income up 224.24% vs LY creating leverage
B Sales up 45.42% vs LY while Total income up 176.79% vs LY creating leverage

有没有办法从上述循环生成的输出行创建一个新的数据帧。

预期输出1:

df:
     String
0    A Sales up 184.37% vs LY while Total income up 224.24% vs LY creating leverage
1    B Sales up 45.42% vs LY while Total income up 176.79% vs LY creating leverage

预期输出2:

df:
     String
0    A Sales up 184.37% vs LY while Total income up 224.24% vs LY creating leverage; B Sales up 45.42% vs LY while Total income up 176.79% vs LY creating leverage

我尝试了以下方法,但它不正确或语法错误:

column_names = ['String']
df= pd.DataFrame(columns = column_names)
df= pd.DataFrame({'Insight': c_1}, index=[0])

最佳答案

为了充实@Cedroc Zoppolo 的评论,这里是一个带有 f 字符串的最小示例。

    import pandas as pd

    df = pd.DataFrame({'Sales': [10, 20], 'Income': [20, -30]})
    
    def description(sales, income):
        return f'Sales up {sales}% while Total income {"up" if income > 0 else "down"} {income}%'

    df['descr'] = df.apply(lambda x: description(x['Sales'], x['Income']), axis=1)

输出:

   Sales  Income                                      descr
0     10      20     Sales up 10% while Total income up 20%
1     20     -30  Sales up 20% while Total income down -30%

关于python - 从 for 循环的输出创建 pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63234176/

相关文章:

Python正则表达式匹配<之前的单词

python - 为连续事件组创建连续事件 ID

pandas - 在数据框中使用带有条件的变换

python - 根据另一个 Pandas 数据框中的重叠范围以及同一范围的总和值映射 2 列的范围

Python sqrt 限制非常大的数字?

python - boto.ec2.connection.EC2Connection.request_spot_instances() 不返回 boto.ec2.spotinstancerequest.SpotInstanceRequest

python - pd.concat(array).groupby ('date' .sum() 返回意外行为

python - 根据 groupby 值从 Pandas 数据框中删除行

python - Panda AssertionError 列已传递,传递的数据有 2 列

python - 向python对象添加属性