【问题标题】:Append columns to Pandas Dataframe将列附加到 Pandas 数据框
【发布时间】:2020-04-09 16:17:40
【问题描述】:

在 Pandas Dataframe 中附加额外的列非常困难

作为测试,我设置了以下代码:

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=';')

总的来说,这似乎工作得很好。仅在 .csv 文件中,我的“Col_1”数据移至“Month”数据。 “Col_2”中的数据移至“Col_1”。 “Col_2”保持为空。新列“Test”和“Test2”很好地添加到其中。 为什么现有数据向左移动?我相信这是非常简单/愚蠢的事情,但它困扰了我几个小时。一些帮助将不胜感激。

enter image description here

【问题讨论】:

  • 这可能是一个错误。做df.reset_index().to_csv(...)

标签: python pandas


【解决方案1】:

问题在于测试字符串中第 2-5 行末尾的分隔符 ;。他们欺骗解析器认为有一个额外的列(没有内容)。

如果删除它们,结果如预期(我只打印到屏幕,不写入文件):

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

【讨论】:

    猜你喜欢
    • 2021-08-15
    • 1970-01-01
    • 2018-10-28
    • 2018-07-20
    • 1970-01-01
    • 2014-07-07
    • 2019-01-22
    • 2021-06-06
    • 2021-03-15
    相关资源
    最近更新 更多