[英]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:生成的文件如下所示:
Time Point A B C ...
1 23 65 98
2 10 24 85
3 1 54 72
4 33 77 0
5 7 73 81
6 122 43 5 # <- row added with new Time Point
PS The Row which is being appended doesn't have a Time Point value and looks like this: PS 附加的行没有时间点值,看起来像这样:
Well ID Cell Count
A 100
B 200
C 54
D 77
E 73
F 49
The resulting file shouldn't have the headers of the first file added either ('Well ID','Cell Count');生成的文件不应添加第一个文件的标题('Well ID'、'Cell Count'); so just the values of the 'Cell Count' column.
所以只是“细胞计数”列的值。
Please, help:(请帮忙:(
Try the following code and check the output CSV file:尝试以下代码并检查 output CSV 文件:
import io
import pandas as pd
# Load an empty CSV file and read it as dataframe
empty_csv = 'Time Point;A;B;C;D;E;F'
df = pd.read_csv(io.StringIO(empty_csv), sep=';')
# Load a CSV file which will be added to `df` defined above
add_csv = 'Well ID;Cell Count\nA;100\nB;200\nC;54\nD;77\nE;73\nF;49\n'
df_add = pd.read_csv(io.StringIO(add_csv), sep=';')
def append_a_row(df, df_add):
df_add = df_add.set_index('Well ID').T
df_add.insert(0, 'Time Point', len(df)+1)
return df.append(df_add)
df_new = append_a_row(df, df_add)
# Save as csv
d = 'path_to_the_output.csv'
df_new.to_csv(d, sep=';', index=False)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.