删除熊猫列名称中的小数

时间:2018-08-10 10:49:44

标签: python pandas numpy dataframe

我有一个以import cv2 import matplotlib.pyplot as plt import time def main(): imgPath="/home/unikx/1_project/codes/batman.jpg" imgPath2="/home/unikx/1_project/codes/batman2.jpg" img1=cv2.imread(imgPath,1) img2=cv2.imread(imgPath2,1) img1=cv2.cvtColor(img1,cv2.COLOR_BGR2RGB) img2=cv2.cvtColor(img2,cv2.COLOR_BGR2RGB) plt.subplot(1,1,1) plt.imshow(img1) plt.title("Image 1") plt.xticks([]) plt.yticks([]) plt.show(block=False) time.sleep(2) plt.close() plt.subplot(1,1,1) plt.imshow(img2) plt.title("Image 2") plt.xticks([]) plt.yticks([]) plt.show(block=False) time.sleep(2) plt.close() plt.imshow(img1) plt.title("Again Image 1") plt.xticks([]) plt.yticks([]) plt.show() time.sleep(2) plt.close() import matplotlib matplotlib.pyplot.close("all") if __name__=="__main__": main() 作为列名的数据框。

numpy.float64

我想将它们更改为字符串并删除小数位:

df =
     2006.0   2007.0   2008.0   2009.0
0       foo      foo      bar      bar
1       foo      foo      bar      bar

我尝试使用df = 2006 2007 2008 2009 0 foo foo bar bar 1 foo foo bar bar 将列保存到列表中并在其中进行更改,但是我没有运气。

任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:3)

您可以使用.astype

转换类型
In [312]: df.columns = df.columns.astype(int)

In [313]: df
Out[313]:
  2006 2007 2008 2009
0  foo  foo  bar  bar
1  foo  foo  bar  bar

或使用.map并转换为字符串类型。

In [338]: df.columns.map('{:g}'.format)
Out[338]: Index(['2006', '2007', '2008', '2009'], dtype='object')

In [319]: df.columns.map(int)
Out[319]: Int64Index([2006, 2007, 2008, 2009], dtype='int64')

答案 1 :(得分:1)

您可以先转换为float,然后再转换为int

str

似乎long之以鼻,但至少我们正在使用底层的NumPy数组。

答案 2 :(得分:0)

using numpy:
>>> df.columns = np.int64(df.columns).astype(str)