基本Pandas数据分析:连接数据类型

时间:2016-02-24 23:45:12

标签: python pandas type-conversion

我加载了一个数据框,其中有一个名为natvty的变量,其频率为50 - 600.每个数字代表一个国家,每个国家/地区出现不止一次。我计算了每个国家在列表中出现的次数。现在我想用国家名称替换国家的号码,例如(57 =美国)。我试过各种for循环无济于事。到目前为止,这是我的代码。在值计数表中,国家/地区编号位于左侧,其显示在数据中的次数位于右侧。我需要用国家名称替换左边的数字。与国家/地区名称对应的数字位于两列的外部Excel工作表中。感谢。

enter image description here

4 个答案:

答案 0 :(得分:1)

我认为最初可能没有必要用国家名称替换国家/地区号码。由于您现在有两个表,一个是列+,另一个(您的excel表可以导出为["country_number", "natvty"]文件,并由.csv读取)是列{{1} },所以你可以简单地加入它们并保留它们。结果表将分别有3列:pandas

["country_number", "country_name"]

确保它们都有一列["country_number", "natvty", "country_name"]。您可以手动修改数据源文件中的表头,或将其视为import pandas as pd df_nav = pd.read_csv("my_natvty.csv") df_cnames = pd.read_csv("excel_country_names.csv") # or use pd.read_excel("country_names.xlsx") directly on excel files df_nav_with_cnames = df_nav.join(df_cnames, on='country_number') 以类似地应用"country_number"。这个概念有点像关系数据库中的SQL操作。

文档:http://pandas.pydata.org/pandas-docs/stable/merging.html

答案 1 :(得分:1)

对于这类事情,我总是更喜欢from urllib.parse import urlsplit, urlunsplit split_url = urlsplit('http://127.0.0.1/asdf/login.php?q=abc#stackoverflow') # You now have: # split_url.scheme "http" # split_url.netloc "127.0.0.1" # split_url.path "/asdf/login.php" # split_url.query "q=abc" # split_url.fragment "stackoverflow" # Use all the path except everything after the last '/' clean_path = "".join(split_url.path.rpartition("/")[:-1]) # "/asdf/" # urlunsplit joins a urlsplit tuple clean_url = urlunsplit(split_url) # "http://127.0.0.1/asdf/login.php?q=abc#stackoverflow" # A more advanced example advanced_split_url = urlsplit('http://foo:bar@127.0.0.1:5000/asdf/login.php?q=abc#stackoverflow') # You now have *in addition* to the above: # advanced_split_url.username "foo" # advanced_split_url.password "bar" # advanced_split_url.hostname "127.0.0.1" # advanced_split_url.port "5000" 函数,它会吃字典或函数。

$(window).on('resize', function() {
    $('.cnt-wrapper a').attr('href', function() {
        return hrefs[$(window).width() < 480 ? 0 : 1] + $(this).data('pathEnd');
    });
}).trigger('resize');

然后,map。在这里我只需输入它,但您可以从csv或excel文件加载它。然后,您要将密钥设置为索引,并将结果系列转换为字典(import pandas as pd import numpy.random as np In [12]: print # generate data df = pd.DataFrame(data={'natvty':np.randint(low=20,high=500,size=10), 'country':pd.Series([1,2,3,3,3,2,1,1,2,3])}) df country natvty 0 1 24 1 2 310 2 3 88 3 3 459 4 3 38 5 2 63 6 1 194 7 1 384 8 2 281 9 3 360 )。

dict

然后您只需to_dict()值标签。

countrymap = {1:'US',2:'Canada',3:'Mexico'}

答案 2 :(得分:0)

注意:此处的基本思路与Shellay's answer相同。我只是想演示如何处理两个数据框中的不同列名,以及如何检索所需的每个国家/地区的频率。

您有一个包含国家/地区代码的数据框,另一个数据框将国家/地区代码映射到国家/地区名称。您只需要在国家/地区代码列上加入它们即可。您可以详细了解merging in PandasSQL joins

import pandas as pd

# this is your nativity frame
nt = pd.DataFrame([
    [123],
    [123],
    [456],
    [789],
    [456],
    [456]
], columns=('natvty',))

# this is your country code map
# in reality, use pd.read_excel
cc = pd.DataFrame([
    [123, 'USA'],
    [456, 'Mexico'],
    [789, 'Canada']
], columns=('country_code', 'country_name'))

# perform a join
# now each row has an associated country_name
df = nt.merge(cc, left_on='natvty', right_on='country_code')

# now you can get frequencies on country names instead of country codes
print df.country_name.value_counts(sort=False)

以上的输出是

Canada    1
USA       2
Mexico    3
Name: country_name, dtype: int64

答案 3 :(得分:-1)

我认为字典是你最好的选择。如果您有国家及其代码的字典,例如

country_dict = {333: 'United States', 123: 'Canada', 456: 'Cuba', ...}

你可能有一个国家及其代码的关键,所以你可以通过循环轻松制作字典:

country_dict = {}
for i in country_list:
    country = i[0]  # If you had list of countries and their numbers
    number = i[1]
    country_dict[number] = country

在您拥有此列之后向您的DataFrame添加列应该很简单:

import pandas as pd
df = pd.read_csv('my_data.csv', header=None)
df['country'] = [country_dict[x[0][i]] for i in list(df.index)]

如果国家/地区代码列的索引为0

,则此方法应该有效