python - 循环熊猫数据框
问题描述
我有以下数据框并想做循环:
df = name
a
b
c
d
我试过下面的代码:
for index, row in df.iterrows():
for line in df['name']:
print(index, line)
但我想要的结果是如下的数据框:
df = name name1
a a
a b
a c
a d
b a
b b
b c
b d
etc.
有什么可能的方法吗?我知道这是一个愚蠢的问题,但我是 python 新手
解决方案
一种使用方式pandas.DataFrame.explode
:
df["name1"] = [df["name"] for _ in df["name"]]
df.explode("name1")
输出:
name name1
0 a a
0 a b
0 a c
0 a d
1 b a
1 b b
1 b c
1 b d
2 c a
2 c b
2 c c
2 c d
3 d a
3 d b
3 d c
3 d d
推荐阅读
- javascript - javascript生成只有5的倍数的数组
- java - 如何从外部存储的根目录中删除文件或目录(...可移动 sdcard 根目录)
- javascript - 过渡效果不适用于动态高度
- r - 根据R中的特定行和列选择数据框值
- java - 在 Android/Java 中实现的速度测试速度太低
- python - 元组的字符串列表
- ruby-on-rails - Ruby on Rails:表单成功提交但没有提交到数据库并且没有显示错误
- python - NameError:名称“”未定义
- github-for-windows - 第一次创建远程 github,终端在我的分支上看不到 html 文件
- numpy - 在给定一个参数的情况下绘制指数函数