python - 在 Pandas 循环中合并多个系列

标签 python pandas loops merge series

所以我有一个系列列表如下:

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'

有人可以帮我解决这个问题吗?谢谢。

最佳答案

如果 groupdf1DataFrame 的列表,使用 pandas.concat使用 axis=1,然后通过使用 f-strings 的 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/

相关文章:

python - 如何获取 Pandas DataFrame 中的值索引?

java - 我不明白为什么要做这个 Action ?我只需要解释一下

使用 GNU Parallel 的 Python 管道

python - 生成大量唯一的随机 float32 数字

python - Dataframe 写入 Postgresql 性能不佳

python - 获取一个 Try 语句循环直到获得正确的值

Python:对 graphlab.SFrame 的所有行的一行的不同列进行迭代操作

python - 通过平均前一行值来填充缺失值

python - 为 PyQT5 的 QWebView 提供资源

python - 在Python中,如何根据一列中的值比较两个csv文件并输出第一个文件中与第二个文件不匹配的记录