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:
PS The Row which is being appended doesn't have a Time Point value and looks like this:
Please, help:(
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.