python - 将 Pandas 数据框列和索引转换为值

标签 python pandas dataframe transformation

我有一个“是/否”格式的数据框,例如

    7   22
1   NaN t
25  t   NaN
其中“t”代表是,我需要将其转换为 X-Y 表,因为列名是 X 坐标,索引是 Y 坐标:
  X  Y
1 22  1
2  7 25
一个伪代码,如:
if a cell = "t":
     newdf.X = df.column(t)
     newdf.Y = df.index(t)

最佳答案

尝试这个:

# Use np.where to get the integer location of the 't's in the dataframe
r, c = np.where(df == 't')

# Use dataframe constructor with dataframe indexes to define X, Y
df_out = pd.DataFrame({'X':df.columns[c], 'Y':df.index[r]})
df_out
输出:
    X   Y
0  22   1
1   7  25
更新地址 @RajeshC comment :
给定 df,
      7   22
1   NaN    t
13  NaN  NaN
25    t  NaN
然后:
r, c = np.where(df == 't')
df_out = pd.DataFrame({'X':df.columns[c], 'Y':df.index[r]}, index=r)
df_out = df_out.reindex(range(df.shape[0]))
df_out
输出:
     X     Y
0   22   1.0
1  NaN   NaN
2    7  25.0

关于python - 将 Pandas 数据框列和索引转换为值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66972735/

相关文章:

python - 在 Python 中将表示为 <number>[m|h|d|s|w] 的时间字符串转换为秒

python - 有没有办法用相应的大陆来标记一个区域? Python

python - 加速时间戳操作

python - 从列表中制作字典并分成两部分

python - 加载 psycopg2 模块时出错 : dlopen with virtualenv django python 2. 7

python - matplotlib savefig() 大小控制

python - 从基于文件的列和行中的最大值中删除重复项 -pandas

python - 在 pandas DataFrame 中计算每列行中的重复项

python - 包含 pandas 数据框的数组和矩阵的字典列表

python - 是否可以将 render_to_response 模板从 django 保存到服务器?