简体   繁体   English

Append 列到 Pandas Dataframe

[英]Append columns to Pandas Dataframe

Pretty stuck with appending extra columns at a Pandas Dataframe在 Pandas Dataframe 处附加额外的列非常困难

As a test I setup the code below:作为测试,我设置了以下代码:

def dataSerialize(TagModel):

    test = """Month; Col_1; Col_2
            1; 0,121; 0,123;
            2; 0,231; 0,356;
            3; 0,150; 0,156;
            4; 0,264; 0,426;
            4; 0,264; 0,426"""

    df = pd.read_csv(StringIO(test), decimal=',',sep=';')
    df = df.set_index('Month')
    df['Test'] = ['3','6','8','78','10']
    df['Test2'] = ['3','6','8','78','10']
    df.to_csv('SerializeTest.csv',sep=';')

In general this seems to work good.一般来说,这似乎工作得很好。 Only in the.csv file, my data from "Col_1" moved to the data from "Month".仅在.csv 文件中,我的“Col_1”数据移动到“Month”数据。 Data from "Col_2" moved to "Col_1". “Col_2”中的数据移至“Col_1”。 "Col_2" stays empty. “Col_2”保持为空。 The new columns "Test" and "Test2" where nicely added to it.新列“Test”和“Test2”很好地添加到其中。 Why the existing data moves to the left?为什么现有数据向左移动? I believe it is something very simple/stupid but it bothers me for hours.我相信这是非常简单/愚蠢的事情,但它困扰了我好几个小时。 Some help would be appreciated very much.一些帮助将不胜感激。

enter image description here在此处输入图像描述

The problem are the delimiters ;问题是分隔符; at the end of the lines 2-5 in the test string.在测试字符串第 2-5 行的末尾。 They trick the parser into thinking that there is an additional column (without content).他们欺骗解析器认为有一个额外的列(没有内容)。

If you remove them, the result is as expected (I only print to screen, don't write to file):如果您删除它们,结果如预期(我只打印到屏幕,不写入文件):

import pandas as pd
from io import StringIO

test = """Month; Col_1; Col_2
            1; 0,121; 0,123
            2; 0,231; 0,356
            3; 0,150; 0,156
            4; 0,264; 0,426
            4; 0,264; 0,426"""

df = pd.read_csv(StringIO(test), decimal=',',sep=';')
df = df.set_index('Month')

df['Test'] = ['3','6','8','78','10']
df['Test2'] = ['3','6','8','78','10']

print(df)

# output
        Col_1   Col_2 Test Test2
Month                           
1       0.121   0.123    3     3
2       0.231   0.356    6     6
3       0.150   0.156    8     8
4       0.264   0.426   78    78
4       0.264   0.426   10    10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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