【问题标题】:Appending row to dataframe with concat()使用 concat() 将行附加到数据帧
【发布时间】:2022-02-16 04:01:17
【问题描述】:

我已经定义了一个空数据框

df = pd.DataFrame(columns=['Name', 'Weight', 'Sample'])

并希望在 for 循环中添加行,如下所示:

for key in my_dict:
   ...
   row = {'Name':key, 'Weight':wg, 'Sample':sm}
   df = pd.concat(row, axis=1, ignore_index=True) 

但我得到了这个错误

cannot concatenate object of type '<class 'str'>'; only Series and DataFrame objs are valid

如果我使用df = df.append(row, ignore_index=True),它可以工作,但似乎append 已被弃用。所以,我想使用concat()。我该如何解决?

【问题讨论】:

  • 如果你收集一个列表中的所有字典并连接一次,效率会更高。

标签: python pandas dataframe


【解决方案1】:

你可以在 pandas DataFrame 中转换你的 dic

import pandas as pd
df = pd.DataFrame(columns=['Name', 'Weight', 'Sample'])
for key in my_dict:
  ...
  #transform your dic in DataFrame
  new_df = pd.DataFrame([row])
  df = pd.concat([df, new_df], axis=0, ignore_index=True)

【讨论】:

    【解决方案2】:

    Concat 需要一个系列或 df 对象的列表作为第一个参数。

    import pandas as pd
    
    my_dict = {'the_key': 'the_value'}
    
    for key in my_dict:
       row = {'Name': 'name_test', 'Weight':'weight_test', 'Sample':'sample_test'}
       df = pd.concat([pd.DataFrame(row, index=[key])], axis=1, ignore_index=True) 
    
    print(df)
             0          1           2
    the_key name_test   weight_test sample_test
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 2020-09-13
      • 2018-04-14
      • 1970-01-01
      • 1970-01-01
      • 2017-10-21
      相关资源
      最近更新 更多