Skip to main content
 首页 » 编程设计

Python之从 csv 文件创建数据帧并将这些数据帧合并在一起

2025年01月19日9oomusou

我在将服务数据帧合并在一起时遇到问题。我下载了一些历史交易数据并将其保存到 csv 文件中。所以现在我想将 cvs 文件中的数据读入多个数据帧并提取一些收盘价。

我创建了一个名为 read_dataset 的函数,它将数据读入数据帧并返回该数据帧。

结合 for 循环,我将所有数据帧存储在字典中。 Dict 键是货币的缩写(参见 coin_list 数据框)。

# List of available coins, saved in a DataFrame called coin_list 
coins = { 'Bitcoin': 'BTC', 'Ethereum': 'ETH', 'Ripple': 'XRP', 'BitcoinCash': 'BCH', 'Litecoin':'LTC', 'EOS': 'EOS', 
          'Tronix': 'TRX', 'Stellar' : 'XLM', 'Neo' : 'NEO', 'Cardano': 'ADA', 'IOTA' : 'IOT', 'Monero': 'XMR'} 
 
# Create a coin list as Dataframe of the dictionary above 
coin_list = pd.DataFrame(list(coins.items()), index = np.arange(0,12), columns=('Currency', 'Abbreviation'), dtype=str) 
 
# Read data into DataFrames 
def read_dataset (filename): 
    print('Reading data from %s' % filename) 
    file = pd.read_csv(filename) 
    file = file.drop('Unnamed: 0', axis=1) 
    return file 
 
# Read all cryptocurrency data into a dictionary of dataframes. 
currency_data = {} 
df = pd.DataFrame() 
for currency in coin_list['Abbreviation']: 
    df = read_dataset(currency + '_historical_data_daily_updated') 
    df = df.set_index('Timestamp') 
    currency_data[currency] = df 
 
currency_data 
Out:  
{'ADA':      close    high     low    open   volumefrom     volumeto 
 Timestamp                                                            
 2017-12-30  0.5900  0.6941  0.4200  0.4955  24118261.70  14016860.69 
 2017-12-31  0.7100  0.7400  0.5900  0.5900  13107255.34   8971147.70 
 2018-01-01  0.7022  0.7150  0.6320  0.7100  13805601.70   9403559.91 
 2018-01-02  0.7620  0.8000  0.6750  0.7022   8440669.40   6292466.84 

因此,在创建字典 currency_data 之后,我想访问和分离包含在 currency_data 中的数据帧。因此,我想创建一个 for 循环,例如将数据帧的所有收盘价合并到一个数据帧中。

有人知道我该如何实现吗?

我可以使用以下代码对两个数据帧执行此操作,但无法将其转换为 for 循环。

a = pd.DataFrame() 
a['ADA closeprice'] = currency_data['ADA']['close'] 
b = pd.DataFrame() 
b['BTC closeprice'] = currency_data['BTC']['close'] 
c = pd.merge(a, b, left_index=True, right_index=True) 
c.drop_duplicates() 
c.head() 
 
ADA closeprice  BTC closeprice 
Timestamp                                  
2017-12-30          0.5900        12531.52 
2017-12-31          0.7100        13850.40 
2018-01-01          0.7022        13444.88 
2018-01-02          0.7620        14754.13 
2018-01-03          1.1000        15156.62 

或者是否有更好的方法从 cvs 文件创建不同的数据帧并将其存储在字典中?

感谢您的帮助!

请您参考如下方法:

为此,您不需要显式的 for 循环。

您可以使用字典理解来提取系列并重命名。然后通过 pd.concat 沿轴连接您的数据帧。

import pandas as pd 
 
# dataframe dict 
d = {'a': pd.DataFrame({'close': [1, 2, 3, 4, 5]}), 
     'b': pd.DataFrame({'close': [6, 7, 8, 9, 10]})} 
 
# series dict with renaming 
s = {k: v['close'].rename(k+'_close') for k, v in d.items()} 
 
# concatenate series along axis=1 
res = pd.concat(list(s.values()), axis=1) 
 
print(res) 
 
#    a_close  b_close 
# 0        1        6 
# 1        2        7 
# 2        3        8 
# 3        4        9 
# 4        5       10 

请注意,串联将对齐每个 pd.Series 的索引。这里的索引是微不足道的(整数),但在您的情况下,它们将是 pd.Timestamp 对象。