有一个字典列表d
,其中x
是一个嵌入列表,例如
d = [{"name":"Python", "x":[0,1,2,3,4,5]}, # x has 300 elements
{"name":"C++", "x":[0,1,0,3,4,4]},
{"name":"Java","x":[0,4,5,6,1]}]
我想将 d
转换为 Dataframe
,并为 x
中的每个元素自动添加列,添加的列名有一个前缀 "abc”,例如,
df.columns = ["name", "abc0", "abc1", ..., "abc300"]
我正在寻找一种有效的方法,因为 d
有很多字典。当我手动添加列时,Python 说
PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`
最佳答案
你在找这样的东西吗:
d = [{"name":"Python", "x":[0,1,2,3,4,5]}, # x has 300 elements
{"name":"C++", "x":[0,1,0,3,4,4]},
{"name":"Java","x":[0,4,5,6,1]}]
df = pd.DataFrame(
{
"name": record["name"],
**{f"abc{i}": n for i, n in enumerate(record["x"])}
}
for record in d
)
您的样本结果:
name abc0 abc1 abc2 abc3 abc4 abc5
0 Python 0 1 2 3 4 5.0
1 C++ 0 1 0 3 4 4.0
2 Java 0 4 5 6 1 NaN
关于python - Dataframe 从列表中添加多列,并创建每个列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70285992/