使用for循环创建多个数据框

时间:2020-09-25 02:27:27

标签: python python-3.x for-loop

嗨,我有一个像这样的数据集。

https://i.stack.imgur.com/cjYAW.png

我想使用countryname_df = data.loc[data.location == 'country name'创建多个数据帧。这是一个示例结果:

https://i.stack.imgur.com/UHkQ2.png

我是否可以使用循环for来创建这种格式的文件?

     c_df = data.loc[data.location == c]

2 个答案:

答案 0 :(得分:0)

import pandas as pd

# a minimal example often helps
d = {'country': ['Albania','Bahrain','Congo'], 'sales': [10,20,30]}
df = pd.DataFrame(data=d)

countries=['Albania','Congo']


for c in countries:
     print(df[df['country'] == c])

输出:

country  sales
0  Albania     10
country  sales
2   Congo     30

答案 1 :(得分:0)

以下示例可满足您的需求。

首先创建一个空列表,您将在其中存储所有不同的数据框。

获取独特国家/地区的列表。

import pandas as pd

data = {'country':['USA','USA','CANADA','CANADA','CANADA','SPAIN','SPAIN','PERU','PERU','PERU','PERU','PERU'],
        'col_1': [3, 2, 1, 0,235,2,5,7,9,7,14,346], 
        'col_2': ['a', 'b', 'c', 'd','v','asd','sg','sdg','ery','wqrew','asf','Ùùsd'],
        'col_3':[3234,52345,64534,65652,1234,435,346,7687,969,689689,79,2143]}
df = pd.DataFrame.from_dict(data)



list_of_df = []
unique_countries = set(list(df['country']))
for country in unique_countries:
  list_of_df.append(df.loc[df['country'] == country,:])

# this is the first dataframe of the list.
list_of_df[0]