必须使用某种集合调用索引:将列名称指定给dataframe(Index must be called with a collection of some kind: assign column name to dataframe)
我有reweightTarget如下,我想将其转换为pandas Dataframe。 但是,我收到以下错误:
TypeError:必须使用某种集合调用Index(...),传递't'
如果我删除columns='t' ,它可以正常工作。 任何人都可以解释一下发生了什么?
reweightTarget
Trading dates
2004-01-31 4.35
2004-02-29 4.46
2004-03-31 4.44
2004-04-30 4.39
2004-05-31 4.50
2004-06-30 4.53
2004-07-31 4.63
2004-08-31 4.58
dtype: float64
pd.DataFrame(reweightTarget, columns='t')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in ()
----> 1 pd.DataFrame(reweightTarget, columns='t')
C:\Anaconda3\lib\site-packages\pandas\core\frame.py in __init__(self, data, index, columns, dtype, copy)
253 else:
254 mgr = self._init_ndarray(data, index, columns, dtype=dtype,
--> 255 copy=copy)
256 elif isinstance(data, (list, types.GeneratorType)):
257 if isinstance(data, types.GeneratorType):
C:\Anaconda3\lib\site-packages\pandas\core\frame.py in _init_ndarray(self, values, index, columns, dtype, copy)
421 raise_with_traceback(e)
422
--> 423 index, columns = _get_axes(*values.shape)
424 values = values.T
425
C:\Anaconda3\lib\site-packages\pandas\core\frame.py in _get_axes(N, K, index, columns)
388 columns = _default_index(K)
389 else:
--> 390 columns = _ensure_index(columns)
391 return index, columns
392
C:\Anaconda3\lib\site-packages\pandas\indexes\base.py in _ensure_index(index_like, copy)
3407 index_like = copy(index_like)
3408
-> 3409 return Index(index_like)
3410
3411
C:\Anaconda3\lib\site-packages\pandas\indexes\base.py in __new__(cls, data, dtype, copy, name, fastpath, tupleize_cols, **kwargs)
266 **kwargs)
267 elif data is None or lib.isscalar(data):
--> 268 cls._scalar_data_error(data)
269 else:
270 if (tupleize_cols and isinstance(data, list) and data and
C:\Anaconda3\lib\site-packages\pandas\indexes\base.py in _scalar_data_error(cls, data)
481 raise TypeError('{0}(...) must be called with a collection of some '
482 'kind, {1} was passed'.format(cls.__name__,
--> 483 repr(data)))
484
485 @classmethod
TypeError: Index(...) must be called with a collection of some kind, 't' was passed
I have reweightTarget as follows and I want to convert it to a pandas Dataframe. However, I got following error:
TypeError: Index(...) must be called with a collection of some kind, 't' was passed
If I remove columns='t', it works fine. Can anyone please explain what's going on?
reweightTarget
Trading dates
2004-01-31 4.35
2004-02-29 4.46
2004-03-31 4.44
2004-04-30 4.39
2004-05-31 4.50
2004-06-30 4.53
2004-07-31 4.63
2004-08-31 4.58
dtype: float64
pd.DataFrame(reweightTarget, columns='t')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in ()
----> 1 pd.DataFrame(reweightTarget, columns='t')
C:\Anaconda3\lib\site-packages\pandas\core\frame.py in __init__(self, data, index, columns, dtype, copy)
253 else:
254 mgr = self._init_ndarray(data, index, columns, dtype=dtype,
--> 255 copy=copy)
256 elif isinstance(data, (list, types.GeneratorType)):
257 if isinstance(data, types.GeneratorType):
C:\Anaconda3\lib\site-packages\pandas\core\frame.py in _init_ndarray(self, values, index, columns, dtype, copy)
421 raise_with_traceback(e)
422
--> 423 index, columns = _get_axes(*values.shape)
424 values = values.T
425
C:\Anaconda3\lib\site-packages\pandas\core\frame.py in _get_axes(N, K, index, columns)
388 columns = _default_index(K)
389 else:
--> 390 columns = _ensure_index(columns)
391 return index, columns
392
C:\Anaconda3\lib\site-packages\pandas\indexes\base.py in _ensure_index(index_like, copy)
3407 index_like = copy(index_like)
3408
-> 3409 return Index(index_like)
3410
3411
C:\Anaconda3\lib\site-packages\pandas\indexes\base.py in __new__(cls, data, dtype, copy, name, fastpath, tupleize_cols, **kwargs)
266 **kwargs)
267 elif data is None or lib.isscalar(data):
--> 268 cls._scalar_data_error(data)
269 else:
270 if (tupleize_cols and isinstance(data, list) and data and
C:\Anaconda3\lib\site-packages\pandas\indexes\base.py in _scalar_data_error(cls, data)
481 raise TypeError('{0}(...) must be called with a collection of some '
482 'kind, {1} was passed'.format(cls.__name__,
--> 483 repr(data)))
484
485 @classmethod
TypeError: Index(...) must be called with a collection of some kind, 't' was passed
原文:https://stackoverflow.com/questions/38599912
更新时间:2020-01-11 09:32
最满意答案
列: 索引或类似数组
用于生成框架的列标签。 如果未提供列标签,则默认为np.arange(n)
例:
df3 = DataFrame(np.random.randn(10,5),columns = ['a','b','c','d','e'])
尝试使用:
pd.DataFrame(reweightTarget, columns=['t'])
columns : Index or array-like
Column labels to use for resulting frame. Will default to np.arange(n) if no column labels are provided
Example:
df3 = DataFrame(np.random.randn(10, 5), columns=['a', 'b', 'c', 'd', 'e'])
Try to use:
pd.DataFrame(reweightTarget, columns=['t'])
相关问答
让我们假设我们有一个有效的 data.frame,每行有50行 dat2
1。 如果可以避免,请不要使用assign和get 。 "dat2[,"VAR1"]"在R无效。 您也可以从帮助页面中注意到这一点 assign不派遣赋值方法,因此它不能用于设置向量,名称,属性等的元素。 请注意,分配给附加列表或数据框会更改附加副本而不是原始对象:请参阅附件和附件。 data.frame的列是列表的一个元素 你要找的是[[
...
这里的问题是你传递的只是一个元素,在这种情况下只是该列的字符串标题,如果你将它转换为一个包含单个元素的列表,那么它可以工作: In [97]:
y = df.as_matrix(columns=[df.columns[0]])
y
Out[97]:
array([[0],
[1],
[0]], dtype=int64)
这是你传递的内容: In [101]:
df.columns[0]
Out[101]:
'viz'
所以它等同于: y = df.as_matr
...
这里有一个方法: import numpy as np
import pandas as pd
def pd_sensible_assign(df, **kwargs):
def gen():
for c in df.columns: yield c.name,c
for k,v in kwargs.iteritems(): yield k,v
return pd.DataFrame(gen(), index=df.index, copy=Fals
...
您需要为DataFrame构造函数指定data , index和columns ,如: >>> pd.DataFrame(data=data[1:,1:], # values
... index=data[1:,0], # 1st column as index
... columns=data[0,1:]) # 1st row as the column names
编辑 :如在@joris注释中,您可能需要将以上更改为np.i
...
您可以将labels作为DataFrame返回,其索引与应用该函数的组相同。 def max_bal(df):
max_row = df['col2'].max()
labels = np.where((df['col3'] == 'yep') &
(df['col2'] == max_row),
'Yes',
'No')
return pd.D
...
我认为你需要通过astype为字符串然后应用函数str_to_number : df['new'] = df['TM52_fail_norm'].astype(str).apply(str_to_number)
print (df)
TM52_fail_norm new
0 2 1
1 1 1
2 - 0
3 1 & 2 2
4 1 & 2 & 3 3
5
...
我认为这里需要read_csv和usecols参数来筛选第二列: df = pd.read_csv('df_seg_sample.csv', usecols=[1])
print (df)
rev
0 15.31
1 64.90
2 18.36
3 62.85
4 10.31
5 12.84
6 69.95
7 32.81
但是如果要使用你的解决方案,请为列名添加[]一个项目列表并仅使用DataFrame构造DataFrame : data = [x[1] for x
...
文档: http : //pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html 列: 索引或类似数组 用于生成框架的列标签。 如果未提供列标签,则默认为np.arange(n) 例: df3 = DataFrame(np.random.randn(10,5),columns = ['a','b','c','d','e']) 尝试使用: pd.DataFrame(reweightTarget, columns=['t
...
你可以使用iloc : df.iloc[:, 0]
例: >>> df
a b c
0 1 4 7
1 2 5 8
2 3 6 9
>>> df['a']
0 1
1 2
2 3
Name: a, dtype: int64
>>> df.iloc[:, 0]
0 1
1 2
2 3
Name: a, dtype: int64
You can use iloc: df.iloc[:, 0]
Example: >>> df
...
尝试: A=data.frame(a=1:4,b=11:14)
> A[[paste0(colnames(A)[1],colnames(A)[2])]]
> A
a b ab
1 1 11 11
2 2 12 24
3 3 13 39
4 4 14 56
...忘了你听说过功能assign 。 比如,永远不要再使用它,甚至不要真的考虑它。 它对你来说已经死了。 如果将此应用于您勾画的for循环,请注意,将循环索引设置为1然后引用列i-1将导致问题。 没有列0.
...