Add dataframe values of the same structure without column names

Asked 1 years ago, Updated 1 years ago, 433 views

Add data frames with the same structure without column names,
I wrote like this, but
names=['time', 'traffic']
df1=pd.read_csv(r'file1.csv', index_col=0, names=cols_name)
df2=pd.read_csv(r'file2.csv', index_col=0, names=cols_name)
df_sum=(df1.set_index('time')+df2.set_index('time')).reset_index()
print(df_sum)

An error message has appeared:
None of ['time'] are in the columns

How should I correct it?
I look forward to your kind cooperation.Enter a description of the image here

python pandas

2023-02-20 23:52

1 Answers

In read_csv(), index_col=0 that is, the date and time items are specified in the index, so

  • You should not need to set_index() again
  • The item df['time'] does not exist because it is already specified in the index
One df1.columns# column
# Index (['Traffic', dtype='object')

df1.reset_index().columns#reset_index() and the time item appears.
# Index (['time', 'traffic'], dtype='object')

From the above,

import pandas as pd
importio
csv1 = io.StringIO(' ''
2023/1/1,11
2023/1/2,12
2023/1/3,13
2023/1/4,14
2023/1/5,15
''')
csv2 = io.StringIO(' ''
2023/1/1,21
2023/1/2,22
2023/1/3,23
2023/1/4,24
2023/1/5,25
''')
cols_name = ['time', 'traffic']
df1=pd.read_csv(csv1, index_col=0, names=cols_name)
df2=pd.read_csv(csv2, index_col=0, names=cols_name)
df_sum = df1+df2
display(df_sum)


2023-02-20 23:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.