簡體   English   中英

如何在 python 中附加行時增加 pandas/csv 文件中列的值

[英]How to 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 個,依此類推。

你能幫忙嗎?

生成的文件如下所示:

在此處輸入圖像描述

PS 附加的行沒有時間點值,看起來像這樣: 在此處輸入圖像描述

請幫忙:(

嘗試:

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

設置

>>> %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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM