Python 数据帧的频率图

Python 数据帧的频率图,python,pandas,frequency,Python,Pandas,Frequency,我有一个df,这样: df['user_location'].value_counts() 我想从user\u location列中了解特定国家的频率,如USA,India。然后我想将频率绘制为美国,印度,以及其他。 因此,我想对该列应用一些操作,以便value\u counts()将输出为: India (sum of all frequencies of all the locations in India including cities, states, etc.) USA

我有一个
df
,这样:

df['user_location'].value_counts()
我想从
user\u location
列中了解特定国家的频率,如
USA
India
。然后我想将频率绘制为
美国
印度
,以及
其他
。 因此,我想对该列应用一些操作,以便
value\u counts()
将输出为:

India     (sum of all frequencies of all the locations in India including cities, states, etc.)
USA       (sum of all frequencies of all the locations in the USA including cities, states, etc.)
Others    (sum of all frequencies of the other locations)                    

似乎我应该合并包含相同国家名称的行的频率,并将其他行合并在一起!但是,在处理城市、州等名称时,它似乎很复杂。最有效的方法是什么?

除了@Trenton_McKinney在评论中的回答,如果你需要将不同国家的州/省映射到国家名称,你必须做一些工作来建立这些关联。例如,对于印度和美国,您可以从wikipedia获取其州的列表,并将其映射到您自己的数据,以将其重新标记为各自的国家名称,如下所示:

# Get states of India and USA
in_url = 'https://en.wikipedia.org/wiki/States_and_union_territories_of_India#States_and_Union_territories'
in_states = pd.read_html(in_url)[3].iloc[:, 0].tolist()
us_url = 'https://en.wikipedia.org/wiki/List_of_states_and_territories_of_the_United_States'
us_states = pd.read_html(us_url)[0].iloc[:, 0].tolist()
states = in_states + us_states

# Make a sample dataframe
df = pd.DataFrame({'Country': states})

    Country
0   Andhra Pradesh
1   Arunachal Pradesh
2   Assam
3   Bihar
4   Chhattisgarh
... ...
73  Virginia[E]
74  Washington
75  West Virginia
76  Wisconsin
77  Wyoming
将州名称映射到国家名称:

# Map state names to country name
states_dict = {state: 'India' for state in in_states}
states_dict.update({state: 'USA' for state in us_states})
df['Country'] = df['Country'].map(states_dict)

    Country
0   India
1   India
2   India
3   India
4   India
... ...
73  USA
74  USA
75  USA
76  USA
77  USA

但是从你的数据样本来看,你似乎也有很多边缘案例需要处理。

除了@Trenton_McKinney在评论中的回答,如果你需要将不同国家的州/省映射到国家名称,你必须做一些工作来建立这些关联。例如,对于印度和美国,您可以从wikipedia获取其州的列表,并将其映射到您自己的数据,以将其重新标记为各自的国家名称,如下所示:

# Get states of India and USA
in_url = 'https://en.wikipedia.org/wiki/States_and_union_territories_of_India#States_and_Union_territories'
in_states = pd.read_html(in_url)[3].iloc[:, 0].tolist()
us_url = 'https://en.wikipedia.org/wiki/List_of_states_and_territories_of_the_United_States'
us_states = pd.read_html(us_url)[0].iloc[:, 0].tolist()
states = in_states + us_states

# Make a sample dataframe
df = pd.DataFrame({'Country': states})

    Country
0   Andhra Pradesh
1   Arunachal Pradesh
2   Assam
3   Bihar
4   Chhattisgarh
... ...
73  Virginia[E]
74  Washington
75  West Virginia
76  Wisconsin
77  Wyoming
将州名称映射到国家名称:

# Map state names to country name
states_dict = {state: 'India' for state in in_states}
states_dict.update({state: 'USA' for state in us_states})
df['Country'] = df['Country'].map(states_dict)

    Country
0   India
1   India
2   India
3   India
4   India
... ...
73  USA
74  USA
75  USA
76  USA
77  USA

但从您的数据样本来看,您似乎也需要处理很多边缘案例。

使用前面答案的概念,首先,我尝试获取所有位置,包括城市、工会、州、地区和地区。然后我制作了一个函数
checkl()
,这样它可以检查位置是印度还是美国,然后将其转换为国家名称。最后,该函数已应用于列
df['user\u location']

# Trying to get all the locations of USA and India

import pandas as pd

us_url = 'https://en.wikipedia.org/wiki/List_of_states_and_territories_of_the_United_States'
us_states = pd.read_html(us_url)[0].iloc[:, 0].tolist()
us_cities = pd.read_html(us_url)[0].iloc[:, 1].tolist() + pd.read_html(us_url)[0].iloc[:, 2].tolist() + pd.read_html(us_url)[0].iloc[:, 3].tolist()
us_Federal_district = pd.read_html(us_url)[1].iloc[:, 0].tolist()
us_Inhabited_territories = pd.read_html(us_url)[2].iloc[:, 0].tolist()
us_Uninhabited_territories = pd.read_html(us_url)[3].iloc[:, 0].tolist()
us_Disputed_territories = pd.read_html(us_url)[4].iloc[:, 0].tolist()

us = us_states + us_cities + us_Federal_district + us_Inhabited_territories + us_Uninhabited_territories + us_Disputed_territories

in_url = 'https://en.wikipedia.org/wiki/States_and_union_territories_of_India#States_and_Union_territories'
in_states = pd.read_html(in_url)[3].iloc[:, 0].tolist() + pd.read_html(in_url)[3].iloc[:, 4].tolist() + pd.read_html(in_url)[3].iloc[:, 5].tolist()
in_unions = pd.read_html(in_url)[4].iloc[:, 0].tolist()
ind = in_states + in_unions

usToStr = ' '.join([str(elem) for elem in us])
indToStr = ' '.join([str(elem) for elem in ind]) 


# Country name checker function

def checkl(T): 
    TSplit_space = [x.lower().strip() for x in T.split()]
    TSplit_comma = [x.lower().strip() for x in T.split(',')]
    TSplit = list(set().union(TSplit_space, TSplit_comma))
    res_ind = [ele for ele in ind if(ele in T)]
    res_us = [ele for ele in us if(ele in T)]
  
    if 'india' in TSplit or 'hindustan' in TSplit or 'bharat' in TSplit or T.lower() in indToStr.lower() or bool(res_ind) == True :
        T = 'India'
    elif 'US' in T or 'USA' in T or 'United States' in T or 'usa' in TSplit or 'united state' in TSplit or T.lower() in usToStr.lower() or bool(res_us) == True:
        T = 'USA'
    elif len(T.split(','))>1 :
        if T.split(',')[0] in indToStr or  T.split(',')[1] in indToStr :
             T = 'India'
        elif T.split(',')[0] in usToStr or  T.split(',')[1] in usToStr :
             T = 'USA'
        else:
             T = "Others"
    else:
        T = "Others"
    return T

# Appling the function on the dataframe column

print(df['user_location'].dropna().apply(checkl).value_counts())

我对python编码非常陌生。我认为这段代码可以以更好、更紧凑的形式编写。正如前面的回答中提到的,还有很多边缘案例需要处理。所以,我也加上了它。如果您对提高我的代码的效率和可读性提出任何批评和建议,我将不胜感激。

使用前面答案的概念,首先,我尝试获取所有位置,包括城市、工会、州、地区和地区。然后我制作了一个函数
checkl()
,这样它可以检查位置是印度还是美国,然后将其转换为国家名称。最后,该函数已应用于列
df['user\u location']

# Trying to get all the locations of USA and India

import pandas as pd

us_url = 'https://en.wikipedia.org/wiki/List_of_states_and_territories_of_the_United_States'
us_states = pd.read_html(us_url)[0].iloc[:, 0].tolist()
us_cities = pd.read_html(us_url)[0].iloc[:, 1].tolist() + pd.read_html(us_url)[0].iloc[:, 2].tolist() + pd.read_html(us_url)[0].iloc[:, 3].tolist()
us_Federal_district = pd.read_html(us_url)[1].iloc[:, 0].tolist()
us_Inhabited_territories = pd.read_html(us_url)[2].iloc[:, 0].tolist()
us_Uninhabited_territories = pd.read_html(us_url)[3].iloc[:, 0].tolist()
us_Disputed_territories = pd.read_html(us_url)[4].iloc[:, 0].tolist()

us = us_states + us_cities + us_Federal_district + us_Inhabited_territories + us_Uninhabited_territories + us_Disputed_territories

in_url = 'https://en.wikipedia.org/wiki/States_and_union_territories_of_India#States_and_Union_territories'
in_states = pd.read_html(in_url)[3].iloc[:, 0].tolist() + pd.read_html(in_url)[3].iloc[:, 4].tolist() + pd.read_html(in_url)[3].iloc[:, 5].tolist()
in_unions = pd.read_html(in_url)[4].iloc[:, 0].tolist()
ind = in_states + in_unions

usToStr = ' '.join([str(elem) for elem in us])
indToStr = ' '.join([str(elem) for elem in ind]) 


# Country name checker function

def checkl(T): 
    TSplit_space = [x.lower().strip() for x in T.split()]
    TSplit_comma = [x.lower().strip() for x in T.split(',')]
    TSplit = list(set().union(TSplit_space, TSplit_comma))
    res_ind = [ele for ele in ind if(ele in T)]
    res_us = [ele for ele in us if(ele in T)]
  
    if 'india' in TSplit or 'hindustan' in TSplit or 'bharat' in TSplit or T.lower() in indToStr.lower() or bool(res_ind) == True :
        T = 'India'
    elif 'US' in T or 'USA' in T or 'United States' in T or 'usa' in TSplit or 'united state' in TSplit or T.lower() in usToStr.lower() or bool(res_us) == True:
        T = 'USA'
    elif len(T.split(','))>1 :
        if T.split(',')[0] in indToStr or  T.split(',')[1] in indToStr :
             T = 'India'
        elif T.split(',')[0] in usToStr or  T.split(',')[1] in usToStr :
             T = 'USA'
        else:
             T = "Others"
    else:
        T = "Others"
    return T

# Appling the function on the dataframe column

print(df['user_location'].dropna().apply(checkl).value_counts())

我对python编码非常陌生。我认为这段代码可以以更好、更紧凑的形式编写。正如前面的回答中提到的,还有很多边缘案例需要处理。所以,我也加上了它。如果您对提高我的代码的效率和可读性提出任何批评和建议,我们将不胜感激。

df['user\u location'].value\u counts()[['used'、'India']]
&
df['user\u location'].value\u counts()[['used'、'India']].plot.bar()
。如果您看得对,数据框包含许多其他行,其中包含名称
印度
美国
,并且以不同的方式,有些行包含
美国
,有些行包含名称
美国
!您可能希望将备用名称映射到单个名称(例如,
df['user\u location']=df['user\u location'].map({'USA':'United'})
)。是的,不仅是备选名称,而且还想结合其州,比如我想显示
印度
印度新德里
印度孟买
。。。用一个名字。基本上,我想在国家层面而非国家层面上显示频率。如果有任何批评和建议可以提高我对这个问题的解决方案的效率和可读性,我将不胜感激:
df['user\u location'].value\u counts()[[['used','India']
&
df['user\u location'].value\u counts()[['used','India'].plot.bar()
。如果您看得正确,数据框包含许多其他行,其中包含名称
India
USA
,并且以不同的方式,一些行包含
USA
,一些行包含名称
USA
!您可能希望将备用名称映射到单个名称(例如,
df['user\u location']=df['user\u location'].map({'USA':'United'})
)。是的,不仅是备选名称,而且还想结合其州,比如我想显示
印度
印度新德里
印度孟买
。。。用一个名字。基本上,我想在国家层面而非国家层面上展示频率。对于提高我的解决方案的效率和可读性的任何批评和建议,我们将不胜感激:对于提高我的解决方案的效率和可读性的任何批评和建议,我们将不胜感激。如果您对提高我的解决方案的效率和可读性提出任何批评和建议,我们将不胜感激。