[英]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:我有这段代码,它从 csv 文件中选择一列并将其作为一行附加到另一个 csv 文件:
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.可以看到,有一个Time Point列,每追加一行,我想让这一列的值加1,比如追加第一行时为0,第二行会有 1 个,第三行将有 3 个,依此类推。
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: PS 附加的行没有时间点值,看起来像这样:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.