简体   繁体   English

在 For 循环中重命名并创建 dataframe?

[英]Rename and create a dataframe inside a For loop?

i have a list ['jan','feb'] and i am trying to loop in a for loop for creating a dataframe我有一个列表['jan','feb']并且我试图在 for 循环中循环以创建 dataframe

    name = ['jan','feb']
    for month in name:
       df = pd.DataFrame(name, columns = ['month'])

This is the current output i'm getting.这是我得到的当前 output。

df df

           month
        0    jan
        1    feb

What i required is to creating a df w.r.t to the values in list.我需要的是为列表中的值创建一个 df w.r.t。 So when 1st value in list is passed 'jan' .因此,当列表中的第一个值通过'jan'时。

Is there a way to rename and creating the df while looping?有没有办法在循环时重命名和创建 df?

jan一月

           month
        0    jan

feb二月

           month
        0    feb

In the example you are giving, you are recreating the same dataframe over and over again.在您给出的示例中,您一遍又一遍地重新创建相同的 dataframe。 You would achieve the same with a simple你可以用一个简单的方法来达到同样的效果

   df = pd.DataFrame(name, columns = ['month'])

You are not using the loop variable month in the loop.您没有在循环中使用循环变量month

I believe you want to create multiple dataframes, one for each month.我相信您想创建多个数据框,每个月一个。 To do this, you could use a dictionary:为此,您可以使用字典:

import pandas as pd

df_dict = {}

name = ['jan','feb']
for month in name:
    df_dict[month] = pd.DataFrame([month])

for month in name:
    print("key: ", month)    
    print("dataframe:")
    print(df_dict[month], end='\n\n')

resulting in导致

key:  jan
dataframe:
     0
0  jan

key:  feb
dataframe:
     0
0  feb

In order to create variables (though I am not sure why you would want to do this), you can modify the above code as follows:为了创建变量(虽然我不确定你为什么要这样做),你可以修改上面的代码如下:

import pandas as pd

name = ['jan','feb']
for month in name:
    globals()[month] = pd.DataFrame([month])

print(jan)
print(feb)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM