'How to increment a value of column in pandas/csv file when the row is appended in python

I have this code which selects a column from a csv file and appends it as a row to another csv file:

def append_pandas(s,d):
    import pandas as pd
    df = pd.read_csv(s, sep=';', header=None)
    df_t = df.T
    df_t.iloc[0:1, 0:1] = 'Time Point'
    df_t.columns = df_t.iloc[0]
    df_new = df_t.drop(0)
    pdb = pd.read_csv(d, sep=';')
    newpd = pdb.append(df_new)
    from pandas import DataFrame
    newpd.to_csv(d, sep=';')

As you can see, there is a Time Point column, and every time the row is appended, I want the value in this column to increment by 1. For example, when the first row is appended, it is 0, the second row will have 1, the third row will have 3 etc.

Could you please help with this?

The resulting file looks like this:

enter image description here

P.S. The Row which is being appended doesn't have a Time Point value and looks like this:enter image description here

Please, help :(



Solution 1:[1]

Try:

df1 = pd.read_csv('data1.csv')
df2 = pd.read_csv('data2.csv', index_col=0).T
df2['Time Point'] = df1['Time Point'].iloc[-1] + 1
out = pd.concat([df1, df2], ignore_index=True)
out.to_csv('out.csv', index=False)
print(out)

# Output
   Time Point    A   B
0           1   23  65
1           2   10  24
2           3    1  54
3           4   33  77
4           5    7  73
5           6  122  43  # <- row added with new Time Point

Setup

>>> %cat data1.csv
Time Point,A,B
1,23,65
2,10,24
3,1,54
4,33,77
5,7,73

>>> %cat data2.csv
ID,Count
A,122
B,43

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Corralien