我有一个数据集,其结构如所附图像。您能找到一种使用 Python Pandas 更好地格式化这些数据的方法吗?理想情况下,去掉每列中所有领先的 NAN。解释一下,对于每个名称(name1、name2 等),都有 3 个与其关联的对应列(id、column_1、column_1)。对于第二个名称 (name2),相应的三列从 row + 1 (row2) 开始,将这些列的第一行保留为 NAN(需要摆脱这些 NaN)。并且这种模式在此数据集中继续存在。
你能重新构造这些数据吗(也许需要转置它什么的?) 谢谢!
你可以:
import pandas as pd
# Read the Excel file into a DataFrame
df = pd.read_excel("your\file\path.xlsx", sheet_name="YourSheetName")
# Loop through the DataFrame and replace "NaN" values with values from the next column
for i in range(df.shape[0]):
for j in range(df.shape[1]):
if str(df.iloc[i, j]).strip().lower() == "nan":
try:
df.iloc[i, j] = df.iloc[i, j + 1]
except IndexError:
pass
file_name = 'your\file\path.xlsx'
# creating an ExcelWriter object
with pd.ExcelWriter(file_name) as writer:
df.to_excel(writer, sheet_name='YourSheetName', index=False)
希望这有帮助!