【问题标题】:How can I create a empty dataframe with combined column names?如何创建具有组合列名的空数据框?
【发布时间】:2023-02-14 03:43:31
【问题描述】:
我正在尝试从 .xlsx 文件创建数据框,该文件将单元格中的字符串转换为排列在单个单元格中的多个字符串。
例如,我有一个数据框如下:
列名 1 列名 2
[[[A;B;C], [D;E]]],
[[F;G;H], [I;J]]]]]
我的意图是创建 5 列:“column_name1_1”、“column_name1_2”、“column_name1_3”、“column_name2_1”、“column_name2_2”。列名可以自动化吗?
创建数据框后,我的意图是在第一列中输入数据“A”,在第二列中输入数据“B”,依此类推。 “F”也会出现在第一列,但在“A”之下,“G”会出现在第二列,但在“B”之下。
有什么办法可以达到这个结果吗?如果不创建列的名称,而是按照我上面所述的方式分发信息,这对我也很有用。
我创建了这个将字母分成列表的简单代码:
for headers in df.columns:
for cells in df[headers]:
cells = str(cells)
sublist = cells.split(character)
print(sublist)
我是第一次使用熊猫,这是我的第一篇文章。欢迎任何建议。非常感谢大家!
【问题讨论】:
标签:
python
pandas
dataframe
【解决方案1】:
您可以使用 Pandas 实现此目的。
干得好!
import pandas as pd
# Load the .xlsx file into a Pandas dataframe
df = pd.read_excel("file.xlsx")
# Create a new dataframe to store the split values
split_df = pd.DataFrame()
# Loop through the columns
for headers in df.columns:
# Loop through the cells in each column
for cells in df[headers]:
cells = str(cells)
sublist = cells.split(";")
# Get the number of elements in the sublist
num_elements = len(sublist)
# Create new columns in the split_df dataframe for each element in the sublist
for i in range(num_elements):
column_name = headers + "_" + str(i+1)
split_df[column_name] = sublist[i]
# Reset the index of the split_df dataframe
split_df = split_df.reset_index(drop=True)
# Save the split_df dataframe to a new .xlsx file
split_df.to_excel("split_file.xlsx", index=False)
此代码会将 .xlsx 文件中的值拆分为一个新的数据框,每个值都分为自己的列。新列将根据原始列名和值在列表中的位置命名。然后,新数据框将保存到名为“split_file.xlsx”的新 .xlsx 文件中。