python - 带 f 字符串和 pandas 数据框的 For 循环

标签 python pandas dataframe for-loop f-string

我需要尝试创建两个循环(必须分开):

循环 1) 对于每个水果:

  1. 如果该结果为 True,则保留行
  2. 删除具有重复日期的行(任意行都可以删除)
  3. 将上述结果保存为每个水果的数据框

LOOP 2) 对于创建的每个数据框,在fruit_score上绘制图表日期:

    concat   apple_score  banana_score       date        apple      banana  
1   apple     0.400         0.400        2010-02-12      True        False  
2   banana    0.530         0.300        2010-01-12      False       True   
3   kiwi      0.532          0.200       2010-03-03      False       False  
4   bana      0.634         0.100        2010-03-03      False       True   

我尝试过:

fruits = ['apple',  'banana',   'orange']
for fruit in fruits:
    selected_rows = df[df[ fruit ] == True ]
    df_f'{fruit}' = selected_rows.drop_duplicates(subset='date')

for fruit in fruits:
    df_f'{fruit}'.plot(x="date", y=(f'{fruit}_score'), kind="line")

最佳答案

你应该按照@youyoun建议的方式做一些事情:

dfs = {}
fruits = ['apple',  'banana']
for fruit in fruits:
    selected_rows = df[df[ fruit ] == True ].drop_duplicates(subset='date')
    dfs[f'df_{fruit}'] = selected_rows

for a,v in dfs.items():
    print(a)
    print(v)

输出:

df_apple
  concat  apple_score  banana_score        date  apple  banana
1  apple          0.4           0.4  2010-02-12   True   False
df_banana
   concat  apple_score  banana_score        date  apple  banana
2  banana        0.530           0.3  2010-01-12  False    True
4    bana        0.634           0.1  2010-03-03  False    True

关于python - 带 f 字符串和 pandas 数据框的 For 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63070372/

相关文章:

Pandas :同一 HDF 中的大型数据帧?

python - Pandas :检查是否存在具有某些值的行

r - 包含点的变量名称问题

python - 字典和字典列表 : conversion and when to use which

python - Python 中的 CMAC-AES

python - 使用 NetworkX 和 Matplotlib 促进网络增长

python - 重新排列 pandas 数据框以形成分组条形图

python - 如何从 Python 编写 Visual Studio 2008 脚本?

python - Seaborn Factorplot的源函数是什么

r - table() 的 as.data.frame 总结频率