所以我有一个系列列表如下:
groupdf1
Out[304]:
[90-95 9
>100 1
80-90 1
50-80 1
Name: bucket, dtype: int64, 80-90 9
95-100 1
90-95 1
50-80 1
Name: bucket, dtype: int64, 80-90 10
90-95 1
50-80 1
Name: bucket, dtype: int64, 80-90 11
95-100 1
Name: bucket, dtype: int64, 50-80 9
我正在尝试创建如下数据框:
bucket.1 bucket.2 bucket.3 bucket.4
90-95 9 1 1 NaN
>100 1 NaN NaN NaN
80-90 1 9 10 11
50-80 1 1 1 NaN
95-100 NaN NaN NaN 1
这基本上是合并索引中的每个系列。我无法循环运行它。我收到以下错误:
groupdf=pd.DataFrame(groupdf1[0])
for i in range(1,len(groupdf1)):
groupdf2=pd.DataFrame(groupdf1[i])
groupdf.concat(groupdf2)
Traceback (most recent call last):
File "<ipython-input-278-4c8876ecdb74>", line 4, in <module>
groupdf.concat(groupdf2)
File "C:\Users\hp1\Anaconda3\lib\site-packages\pandas\core\generic.py", line 3081, in __getattr__
return object.__getattribute__(self, name)
AttributeError: 'DataFrame' object has no attribute 'concat'
有人可以帮我解决这个问题吗?谢谢。
最佳答案
如果 groupdf1
是 DataFrame
的列表,使用 pandas.concat
使用 axis=1
,然后通过使用 f-string
s 的 enumerate
设置新的列名称:
df = pd.concat(groupdf1, axis=1)
df.columns = [f'{x}.{i}' for i, x in enumerate(df.columns, 1)]
#alternative
#df.columns = [f'bucket.{i}' for i in np.arange(1,len(df.columns) + 1)]
关于python - 在 Pandas 循环中合并多个系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52603891/