【问题标题】:Pythonic way of transforming Pandas dataframe转换 Pandas 数据框的 Pythonic 方式
【发布时间】:2019-05-21 01:38:54
【问题描述】:

我有一个类似的数据集;

x1      NAN         
x2      NAN         
x3      NAN     
NAN     y1  
NAN     y2  

有没有办法将熊猫数据框重塑到下面; 我猜它会像 sql 外连接,所以我可以乘以值。

x1  y1      
x1  y2      
x2  y1      
x2  y2          
x3  y1      
x3  y2      

编辑: 原因;我必须将 Excel 文件(我无法控制)转换为这种格式,以提供另一个程序(我无法控制)

    xl = pd.ExcelFile(
    '/inputfile.xlsx')
ncols = xl.book.sheet_by_index(0).ncols
df = xl.parse(0, converters={i: str for i in range(ncols)})

## Maybe this kind of Logic 
## But could it be Pythonic
# for index in range(len(df)):
#     if not pd.isnull(df.iloc[index][3]):
#         print(df.iloc[index][3])


writer = pd.ExcelWriter(
    'output.xlsx')  # engine='xlsxwriter'
df.to_excel(writer, 'Sheet1', index=False)
writer.save()

【问题讨论】:

  • 这种转变的逻辑是什么?
  • 看来外连接是你要找的(拆分原始数据框后),但你的逻辑确实不清楚
  • 逻辑:我必须转换 excel 文件以提供遗留程序。
  • @NeofytosBoufidis 我该怎么做,有sn-p
  • 不明白为什么我的问题降了2分,有什么问题?

标签: python pandas dataframe


【解决方案1】:

您可以从以下快速 hack 开始

df1 = pd.DataFrame(data=df.values.reshape(-1))

for i in df1[0].str.replace('\d+','').unique():
    df1[i] = df1[0]
df1 = df1[df1[0].str.replace('\d+','').dropna().unique()]
for xx in df1.columns:
    df1[xx] = df1[xx].apply(lambda x:x if type(x)==str and x.startswith(df1[xx].name) else np.nan )

df1



        x   c   y   title
     0  x1  NaN NaN NaN
     1  NaN c1  NaN NaN
     2  x2  NaN NaN NaN
     3  NaN c2  y1  NaN
     4  x3  NaN y3  title1
     5  NaN c3  NaN title2
     6  NaN NaN NaN NaN

【讨论】:

    猜你喜欢
    • 2022-01-24
    • 1970-01-01
    • 2012-10-15
    • 1970-01-01
    • 2012-09-05
    • 2020-10-14
    • 2015-05-03
    • 2023-01-15
    相关资源
    最近更新 更多