python - Pandas 生成柱

标签 python pandas

我有以下 df:

from    to  

5   7   

8   10  
我正在尝试获得以下输出:
from    to  zip_1   zip_2   zip_3   zip_4

5   8   5   6   7   8

9   10  9   10      
我尝试了以下代码,但导致错误。
for index, row in df.iterrows():
    zip_index = 0
    colName = 'zip' + '_' + str(zip_index)
    while row[colName] != row.To: 
        zip_index = zip_index + 1
        NewCol = 'zip' + '_' + str(zip_index)
        row[NewCol] = row[colName] + 1
        colName = NewCol
我错过了什么?
谢谢!

最佳答案

您可以使用 pandas.DataFrame.apply :

df2 = df.apply(lambda x: pd.Series(range(x["from"], x["to"] + 1), dtype = "float16"), axis = 1)

df2.columns += 1
df2 = df2.add_prefix("zip_")

df_final = pd.concat([df,df2], axis = 1)
#   from  to  zip_1  zip_2  zip_3  zip_4
#0     5   8    5.0    6.0    7.0    8.0
#1     9  10    9.0   10.0    NaN    NaN

关于python - Pandas 生成柱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65727522/

相关文章:

python - 了解如何在 Python 中使用 COM

python - Pandas :DataFrame.mean() 非常慢。如何更快地计算列的均值?

python - 如何在数据框中指定列和行

python - 将多个相同的 SQLite 查询合并为一个

Python itertools.product 重新排序生成

python - 如何在没有互联网访问和搜索可用的情况下制作本地 Pypi 镜像?

python - 在不对结果进行排序的情况下计算数据帧的模式

python - 抓取字典中字典中值最高的键

python - pandas 加入 DataFrame 强制后缀?

python - 数据帧到字符串