pandas 在python中为for循环的每次迭代添加变量后缀

snz8szmq  于 2023-02-02  发布在  Python
关注(0)|答案(2)|浏览(152)

我搜索了措辞相似的问题,但没有找到一个回答我的问题。
我有2个 Dataframe 显示exam_1exam_2上的结果:

exam_1 = pd.DataFrame([['Jim', 87], ['Toby', 44], ['Joe', 71], ['Tom', 59]], columns=['Name', 'Score'])

exam_2 = pd.DataFrame([['Tom', 88], ['Joe', 55], ['Jim', 62], ['Toby', 70]], columns=['Name', 'Score'])

我想迭代这些 Dataframe ,这样我们:

  • 删除Score小于60的受试者
  • 根据受试者姓名的首字母创建新 Dataframe (JT):
for df in (exam_1, exam_2):
    
    # Remove subjects with score less than 60
    df = df[df['Score'] >= 60]

    # Dataframe of names starting with 'J' or 'T'
    J = df[df['Name'].str.startswith('J')]
    T = df[df['Name'].str.startswith('T')]
    • 我想根据for循环中的迭代为 Dataframe JT添加后缀**

例如,exam_1是第一次迭代,因此 Dataframe 将是J_1T_1
exam_2是第二次迭代,因此 Dataframe 将是J_2T_2
这可能做到吗?

qlzsbp2j

qlzsbp2j1#

也许用enumerateglobals

for idx, df in enumerate((exam_1, exam_2), start=1):
    # Remove subjects with score less than 60
    df = df[df['Score'] >= 60]

    # Dataframe of names starting with 'J' or 'T'
    globals()[f'J_{idx}'] = df[df['Name'].str.startswith('J')]
    globals()[f'T_{idx}'] = df[df['Name'].str.startswith('T')]
  • 注意:这将创建变量(T_1,J_1,T_2和J_2)作为全局作用域中的pandas.core.frame.DataFrame。*
prdp8dxp

prdp8dxp2#

在你的情况下使用法令:

J = {}
T = {}

for i, df in enumerate((exam_1, exam_2), 1):
    
    # Remove subjects with score less than 60
    df = df[df['Score'] >= 60]

    # Dataframe of names starting with 'J' or 'T'
    J[i] = df[df['Name'].str.startswith('J')]
    T[i] = df[df['Name'].str.startswith('T')]

输出:

>>> J[1]
  Name  Score
0  Jim     87
2  Joe     71

>>> J[2]
  Name  Score
2  Jim     62

>>> T[1]  # all scores < 60
Empty DataFrame
Columns: [Name, Score]
Index: []

>>> T[2]
   Name  Score
0   Tom     88
3  Toby     70

相关问题