[英]Convert columns on pandas from non-null object to float
I'm having some difficulties to convert the values from object to float!!!我在将值从 object 转换为浮点数时遇到一些困难!!!
I saw some examples but I couldn't be able to get it.我看到了一些例子,但我无法得到它。
I would like to have a for loop to convert the values in all columns.我想要一个 for 循环来转换所有列中的值。
I didn't have yet a script cause I saw different ways to do it我还没有脚本,因为我看到了不同的方法
Terawatt-hours Total Asia Pacific Total CIS Total Europe
2000 0.428429 0 0.134473
2001 0.608465 0 0.170166
2002 0.829254 0 0.276783
2003 1.11654 0 0.468726
2004 1.46406 0 0.751126
2005 1.85281 0 1.48641
2006 2.29128 0 2.52412
2007 2.74858 0 3.81573
2008 3.3306 0 7.5011
2009 4.3835 7.375e-06 14.1928
2010 6.73875 0.000240125 23.2634
2011 12.1544 0.00182275 46.7135
I tried this:我试过这个:
df = pd.read_excel(r'bp-stats-review-2019-all-data.xls')
columns = list(df.head(0))
for i in range(len(columns)):
df[columns[i]].astype(float)
Your question is not clear as to which column you are trying to convert, So I am sharing the example for the 1st column in your screenshot.您的问题不清楚您要转换哪一列,因此我在屏幕截图中分享第一列的示例。
df['Terawatt-hours'] = df.Terawatt-hours.astype(float)
or same for any other column.或任何其他列相同。
EDIT编辑
for creating a loop on the dataframe and change it for all the columns, you can do the following:要在 dataframe 上创建一个循环并为所有列更改它,您可以执行以下操作:
Generating a dummy dataframe生成一个虚拟 dataframe
df = pd.DataFrame(np.random.randint(0, 100, size=(20, 4)), columns=list('abcd'))
Check the type of column in dataframe:检查dataframe中列的类型:
for column in df.columns:
print(df[column].dtype)
Change the type of all the columns to float将所有列的类型更改为浮动
for column in df.columns:
df[column] = df[column].astype(float)
your question is not clear?你的问题不清楚? which columns are you trying to convert to float and also post what you have done.您要将哪些列转换为浮动并发布您所做的事情。
EDIT:编辑:
what you tried is right until the last line of your code where you failed to reassign the columns.您尝试的是正确的,直到您未能重新分配列的代码的最后一行。 df[columns[i]] = df[columns[i]].astype(float)
also try using df.columns
to get column names instead of list(df.head(0))
也尝试使用df.columns
来获取列名而不是list(df.head(0))
the link here to pandas docs on how to cast a pandas object to a specified dtype 此处指向 pandas 文档的链接,介绍如何将 pandas object 转换为指定的数据类型
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.