如何将数据添加到空pddataframe python

时间:2018-05-31 16:01:48

标签: python list pandas dataframe

我正在尝试将一些数据添加到数据框中,以便将其转换为.csv文件,但我遇到了一个“奇怪”的问题。我的代码如下:

df = pd.DataFrame(columns=[
    ['team'], 
    ['timestamp'], 
    ['tr_jan'], 
    ['tr_dec'], 
    ['tr_diff']])
datapoints = []

#code to get the data for the datapoints list

print(datapoints)

for tuple in datapoints:
    team = tuple[0]
    print(type(team))
    for datapoint in tuple[1]:
        timestamp = get_time_stamp(datapoint[0])
        print(type(timestamp))
        df = df.append({
            'team': team, 
            'timestamp': timestamp,
            'tr_jan': 1,
            'tr_dec': 20,
            'tr_diff': 2000}, ignore_index=True)

print(df)

我尝试做的是使用此数据向数据框添加新行。但是当我运行它时它会给我这个错误/输出:

#Data that I want in the dataframe
[('ADO Den Haag', [['January 2010', 1368, 719], ['December 2010', 1422, 537], ['January 2011', 1455, 389], ['December 2011', 1477, 329], ['January 2012', 1461, 376], ['December 2012', 1443, 451], ['January 2013', 1437, 469], ['December 2013', 1383, 703], ['January 2014', 1386, 691], ['December 2014', 1422, 521], ['January 2015', 1412, 560], ['December 2015', 1461, 385], ['January 2016', 1467, 364], ['December 2016', 1403, 614], ['January 2017', 1382, 715], ['December 2017', 1435, 458], ['January 2018', 1426, 488]])]
#item type of team variable    
<class 'str'>
#item type of timestamp variable
<class 'int'>

     File "preprocessing.py", line 77, in <module>
        main()
      File "preprocessing.py", line 71, in main
        'tr_dec': 2000}, ignore_index=True)
      File "C:\Python36\lib\site-packages\pandas\core\frame.py", line 6188, in append
        self = self.reindex(columns=combined_columns)
      File "C:\Python36\lib\site-packages\pandas\util\_decorators.py", line 186, in wrapper
        return func(*args, **kwargs)
      File "C:\Python36\lib\site-packages\pandas\core\frame.py", line 3563, in reindex
        return super(DataFrame, self).reindex(**kwargs)
      File "C:\Python36\lib\site-packages\pandas\core\generic.py", line 3685, in reindex
        fill_value, copy).__finalize__(self)
      File "C:\Python36\lib\site-packages\pandas\core\frame.py", line 3493, in _reindex_axes
        fill_value, limit, tolerance)
      File "C:\Python36\lib\site-packages\pandas\core\frame.py", line 3515, in _reindex_columns
        tolerance=tolerance)
      File "C:\Python36\lib\site-packages\pandas\core\indexes\multi.py", line 2104, in reindex
        target = MultiIndex.from_tuples(target)
      File "C:\Python36\lib\site-packages\pandas\core\indexes\multi.py", line 1350, in from_tuples
        arrays = list(lib.tuples_to_object_array(tuples).T)
      File "pandas/_libs/src\inference.pyx", line 1542, in pandas._libs.lib.tuples_to_object_array
    TypeError: Expected tuple, got str

我的代码究竟出了什么问题?我遵循了有关数据框架的教程,他的代码几乎相同,但我的代码不起作用。

提前致谢!

0 个答案:

没有答案