【问题标题】:How do I insert a one column Series into a single dataframe column in python?如何将单列系列插入 python 中的单个数据框列?
【发布时间】:2021-08-15 02:11:06
【问题描述】:

我从数据框中取出并复制了一列。简单的。我修改了它,现在我需要把它放回去,但我不知道怎么做。我尝试了无数种方法,但都没有奏效。非常感谢任何帮助。

代码如下: [代码]

for col in ["Shares__Basic_"]:
    tmp_col = data[col]
    count = 0
    index_no = data.columns.get_loc(col)
    while 1:
        result = sm.tsa.stattools.adfuller(tmp_col, autolag='AIC')
        pvalue = result[1]
        if pvalue > 0.01:
            tmp_col = tmp_col.diff()
            count = count + 1
            tmp_col = tmp_col.drop(tmp_col.index[0])
            print(col+" diffed")
        elif pvalue < 0.01:
            break
    while count > 0:
        tmp_col = pd.concat([pd.Series([float("nan")]), tmp_col])
        count = count - 1
    del data[col]
    data.insert(index_no, col, value=tmp_col)

[/代码]

【问题讨论】:

标签: python pandas dataframe series


【解决方案1】:

试试这个在现有列上添加列 -

df = pd.DataFrame({'A':[1,2,3],'B':[4,5,6]}) #DUMMY DATASET
print(df)

#>>    A  B
#>> 0  1  4
#>> 1  2  5
#>> 2  3  6

modified_column = df['A']**2

#Adding it back over the existing columns
df['A'] = modified_column
print(df)

#>>    A  B
#>> 0  1  4
#>> 1  4  5
#>> 2  9  6

如果你想将它添加为附加列,那么试试这个 -

#Adding it back as a new column
df['New_A'] = modified_column
print(df)

#>>    A  B  New_A
#>> 0  1  4      1
#>> 1  2  5      4
#>> 2  3  6      9

编辑:ValueError: cannot reindex from a duplicate axis 通常在您有重复的索引值时发生。您可能不小心损坏了 modified_column 的索引。使用原始数据框的索引重置它。

modified_column.index = df.index

【讨论】:

  • 我最初尝试了你的方法,但它给了我一个错误.....ValueError: cannot reindex from a duplicate axis
  • 如果您不共享示例数据集、您尝试的代码以及您遇到的完整错误,我将无法进一步帮助您。请将这些添加到问题中,我很乐意为您提供帮助。
  • 如何共享数据集?
  • 尝试在我的代码之前添加这个 - df = df.reset_index(drop=True)
  • 你的数据有多大?多少行/列?
【解决方案2】:

使用insert:

df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
s = pd.Series([5, 6])
df.insert(0, "new", s)
print(df)

【讨论】:

  • 它不允许我替换列。如何替换现有的列和值?
  • 我删除了该列并插入了它,但它给了我这个错误....ValueError: cannot reindex from a duplicate axis
  • 如果您使用数据框和系列的示例更新您的问题,它将有所帮助。它可以很短。请参阅我的回答,了解如何从头开始非常轻松地创建数据框和系列。
猜你喜欢
  • 2020-08-15
  • 2021-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-19
  • 2018-06-23
  • 2014-04-21
  • 1970-01-01
相关资源
最近更新 更多