构建Dataframe格式的数据

构建Dataframe格式的数据
数据集中的数据:
intereset-rates.csv
1297228-20181122211553396-371769950.png

populations.csv
1297228-20181122211648389-2111934990.png

# Load the data into Python lists

with open('../data/countries/interest-rates.csv', 'r') as f:
    int_rates_col_names = next(f).strip().split(';')
    int_rates = [line.split(';') for line in f.read().splitlines()]
    
with open('../data/countries/populations.csv', 'r') as f:
    populations_col_names = next(f).strip().split(';')
    populations = [line.split(';') for line in f.read().splitlines()]
import pandas as pd
df_int_rates= pd.DataFrame(int_rates, columns=int_rates_col_names)
df_populations=pd.DataFrame(populations, columns=populations_col_names)
pd.options.diaplay.max_rows=10000
#更改数据的类型
df_int_rates['']=df_int_rates[''].astype(float, copy=False)
df_int_rates['']=pd.to_datetime(df_int_rates[''])
#合并两个DataFrame数据集
df_merge=pd.merge(
                df_populations,
                df_int_rates,
                #按照两个表中的哪两列进行合并
                left_on='Country(or dependency)'
                right_on='Country or currency union',
                #连接的方式,类似于数据库
                how='outer'
                )

1297228-20181122211946920-490434305.png

#更改数据集中某一个位置的值
#比如讲U.S.更改为United States
col='Country(or dependency)'
#对于下一句代码的理解:判断col这一列所有元素是否等于'U.S.',等于就是true,否则是false, 返回的是行号和真假值
mask= df.populations[col]=='U.S.'
df_populations.loc[mask, col]='United States'
#更改列的名字
del df_merge['Country or currency union']
name_map = {'Country (or dependency)': 'Country',
            'Population (2018)': 'Population',
            'Central bank interest rate (%)': 'Interest rate'}
df_merge=df_merge.rename(columns=name_map)

1297228-20181122212030600-373409423.png

转载于:https://www.cnblogs.com/share-sjb/p/10003971.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值