我想要做的事情应该非常简单。基本上,我有一些数据框,我需要将某些元组值赋给某些列。
例如:
pd_tmp = pd.DataFrame(np.random.rand(3,3))
pd_tmp["new_column"] = ("a",2)
我只需要一个包含元组值的新列,我该怎么做?
ValueError: Length of values does not match length of index
之前的代码出现了错误。
你可以将元组包装在列表中:
import pandas as pd
pd_tmp = pd.DataFrame(np.random.rand(3,3))
pd_tmp["new_column"] = [("a",2)] * len(pd_tmp)
pd_tmp
# 0 1 2 new_column
#0 0.835350 0.338516 0.914184 (a, 2)
#1 0.007327 0.418952 0.741958 (a, 2)
#2 0.758607 0.464525 0.400847 (a, 2)
我正在寻找类似的东西,但在我的情况下,我想让元组成为现有列的组合,而不仅仅是固定值。我发现了下面的解决方案,希望与像我一样的其他人分享,并希望它对他们有用。
In [24]: df
Out[24]:
A B
0 1 2
1 11 22
2 111 222
3 1111 2222
In [25]: df['D'] = df[['A','B']].apply(tuple, axis=1)
In [26]: df
Out[26]:
A B D
0 1 2 (1, 2)
1 11 22 (11, 22)
2 111 222 (111, 222)
3 1111 2222 (1111, 2222)
lambda
与 apply
一起使用。pd_tmp.assign(newc_olumn=pd_tmp.apply(lambda x: ('a', 2), 1))
0 1 2 newc_olumn
0 0.373564 0.806956 0.106911 (a, 2)
1 0.332508 0.711735 0.230347 (a, 2)
2 0.516232 0.343266 0.813759 (a, 2)
Series
文档。
所以Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.). The axis labels are collectively referred to as the index. The basic method to create a Series is to call:
>>> s = pd.Series(data, index=index)
Here, data can be many different things:
- a Python dict
- an ndarray
- a scalar value (like 5)
Series
不能直接使用元组类型。ndarray
的元素。Series/Dataframe
的单元格,请参考此问答。如果元组中只有一个数字,请添加逗号:
pd.DataFrame({'no_comma': [(1.9)], 'with_comma': [(1.9,)]})
size = 3
pd.DataFrame(np.random.rand(3,size), [('a',2)]*size )