繁体   English   中英

当在 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

PS 附加的行没有时间点值,看起来像这样:

   Well ID   Cell Count
         A          100
         B          200 
         C           54
         D           77
         E           73
         F           49

生成的文件不应添加第一个文件的标题('Well ID'、'Cell Count'); 所以只是“细胞计数”列的值。

请帮忙:(

尝试以下代码并检查 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM