簡體   English   中英

如何在 pandas dataframe 中插入重復的列,並從新列的值中刪除最后 3 個數字?

[英]How do I insert a duplicated column in a pandas dataframe with the last 3 numbers removed from the values of the new column?

我對此非常陌生。 我在名為“oldcol”的列中有值。 我正在嘗試創建一個新的 dataframe ,它具有 oldcol 和一個新列,其值與 oldcol 中的值相同,但刪除了字符串的最后三位。 我以為我可以使用 insert 方法,但從文檔中意識到我不能以這種方式帶入 oldcol 值。 我嘗試的代碼如下:

### I realize this is not going to work.
df2 = df1.insert(2,
                 column='newcol',
                 value='oldcol')
df2['newcol'] = df2['newcol'] \
    .astype(str).str[:-3] \
        .astype(np.int64)

go 關於這個問題的最佳方法是什么?

嘗試這個:

df['new_col'] = df['old_col'].str[:-3]

這應該可以完成這項工作。 讓我知道它是否有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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