当在 python 中追加行时,增加 pandas/csv 文件中列的值
Increment a value of column in pandas/csv file when the row is appended in python
我有这段代码,它从一个 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=';')
可以看到,有一个Time Point列,每追加一行,我想让这一列的值加1,比如追加第一行时,就是0 ,第二行将有 1,第三行将有 3 等
你能帮忙解决一下吗?
生成的文件如下所示:
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
P.S。附加的行没有时间点值,如下所示:
Well ID Cell Count
A 100
B 200
C 54
D 77
E 73
F 49
生成的文件不应添加第一个文件的 headers ('Well ID','Cell Count');所以只有 'Cell Count' 列的值。
求求你帮忙:(
尝试以下代码并检查输出的 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)
我有这段代码,它从一个 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=';')
可以看到,有一个Time Point列,每追加一行,我想让这一列的值加1,比如追加第一行时,就是0 ,第二行将有 1,第三行将有 3 等
你能帮忙解决一下吗?
生成的文件如下所示:
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
P.S。附加的行没有时间点值,如下所示:
Well ID Cell Count
A 100
B 200
C 54
D 77
E 73
F 49
生成的文件不应添加第一个文件的 headers ('Well ID','Cell Count');所以只有 'Cell Count' 列的值。
求求你帮忙:(
尝试以下代码并检查输出的 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)