根据组对数据帧进行切片,没有连续的字符串

2024-09-29 22:35:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个针对不同国家的问卷调查结果的数据框架,每个国家都有重复的条目。国家在v6中。例如:

v1   v2 ... v6     ...  v550
0    5  ... Belgium...  not important
1    6  ... Belgium...  important
.
.
.
1002  5 ... Belgium ... do not care
1003  3 ... Germany ... important

我知道如何从比利时提取数据

print ('Belgium')
groupBE = dataframe[(dataframe['v6']=='Belgium')]
print ('what is the importance in Belgium')
cforBE = groupBE['v550'].value_counts(sort = False)
print (cforBE)

我想知道是否有一种优雅的方法可以对v6中的26个国家/地区执行相同的操作,而不必为所有国家/地区编写代码。我假设它与groupby()有关,因为这个给了我不同的v6值。而且itertools经常在论坛中被引用,但我无法让它发挥作用。我得到的最接近的方法是临时保存并打印locals()中的国家或下面的代码,但它们都不起作用,因为我不知道如何使变量更改名称

for name, group in dataframe.groupby('v6'):
    print (name)
    c + str(name) = dataframe[(dataframe['v6']=='name')]
    print ('importance in country ' name)
    c + str(name) = c + str(name) ['v550'].value_counts(sort = False)
    print (c + str (name))

Tags: 数据nameindataframenot国家printstr

热门问题