2024-10-01 07:13:42 发布
网友
这个问题可能是非常愚蠢的,但我在想怎么做时伤了我的大脑
有一个包含N列的pd.dataframe。我需要选择一些列,通过列的索引引用,然后将所有值转换为数值,并在我的^{中重写该列
pd.dataframe
我已经通过列名引用(比如df['a'] = pd.to_numeric(df['a']))完成了,但是仍然使用索引(比如df[1] = pd.to_numeric(df[1])
df['a'] = pd.to_numeric(df['a'])
df[1] = pd.to_numeric(df[1])
在这种情况下,dataframe列引用的正确方法是什么?(python 2.7)
dataframe
你可以看看下面的帖子 Is .ix() always better than .loc() and .iloc() since it is faster and supports integer and label access?
必须的 [不同的索引选择](http://pandas.pydata.org/pandas-docs/stable/indexing.html#different-choices-for-indexing)
您可以使用^{}选择列,然后使用^{}^{}:
import pandas as pd df = pd.DataFrame({1:['1','2','3'], 2:[4,5,6], 3:[7,8,9], 4:['1','3','5'], 5:[5,3,6], 6:['7','4','3']}) print (df) 1 2 3 4 5 6 0 1 4 7 1 5 7 1 2 5 8 3 3 4 2 3 6 9 5 6 3 print (df.dtypes) 1 object 2 int64 3 int64 4 object 5 int64 6 object dtype: object print (df.columns) Int64Index([1, 2, 3, 4, 5, 6], dtype='int64')
如果列是strings,则不是int(但看起来像int)将''添加到listcols中的数字:
strings
int
''
list
cols
import pandas as pd df = pd.DataFrame({'1':['1','2','3'], '2':[4,5,6], '3':[7,8,9], '4':['1','3','5'], '5':[5,3,6], '6':['7','4','3']}) #print (df) #print (df.dtypes) print (df.columns) Index(['1', '2', '3', '4', '5', '6'], dtype='object') #add `''` cols = ['1','4','6'] #1. ix: supports mixed integer and label based access df.ix[:, cols] = df.ix[:, cols].apply(pd.to_numeric) #2. loc: only label based access # df.loc[:, cols] = df.loc[:, cols].apply(pd.to_numeric) #3. iloc: for index based access # cols = [i for i in range(len(df.columns))] # df.iloc[:, cols].apply(pd.to_numeric) print (df) 1 2 3 4 5 6 0 1 4 7 1 5 7 1 2 5 8 3 3 4 2 3 6 9 5 6 3 print (df.dtypes) 1 int64 2 int64 3 int64 4 int64 5 int64 6 int64 dtype: object
你可以看看下面的帖子 Is .ix() always better than .loc() and .iloc() since it is faster and supports integer and label access?
必须的 [不同的索引选择](http://pandas.pydata.org/pandas-docs/stable/indexing.html#different-choices-for-indexing)
您可以使用^{} 选择列,然后使用^{} ^{} :
^{pr2}$如果列是
strings
,则不是int
(但看起来像int
)将''
添加到list
cols
中的数字:相关问题 更多 >
编程相关推荐