我有一个类似于以下的数据框:
123 345 456 789
987 876 765 543
... ... ... ...
但是顶部行和最左侧列被视为标题,实际上它们是值。有没有办法将它们向下/向右移动并用默认索引替换它们?
编辑:我已经考虑过设置header=None,但这不是一个选项。数据框是通过read_excel创建的,但程序的许多部分已经使用了.loc等直接引用要删除的标题名称。
针对您的解决方案,只需移动它即可。但如果您正在从任何csv文件中读取数据,则在读取时可以考虑不获取标题(header=None)。
345 456 789
123
987 876 765 543
df.reset_index().T.reset_index().T
输出:
0 1 2 3
index 123 345 456 789
0 987 876 765 543
pd.read_csv('data.csv',header=None)
输出:
0 1 2 3
0 123 345 456 789
1 987 876 765 543
使用参数index_col=[0]
,默认情况下第一行将被转换为列名,因此不需要该参数:
import pandas as pd
temp=u"""123;345;456;789
987;876;765;543"""
#after testing replace 'pd.compat.StringIO(temp)' to 'filename.csv'
df = pd.read_csv(pd.compat.StringIO(temp), sep=";", index_col=[0])
print (df)
345 456 789
123
987 876 765 543
print (df)
0 1 2 3
0 123 345 456 789
1 987 876 765 543
#set first row to columns
df.columns = df.iloc[0]
#remove first row from data and remove columns name
df = df.iloc[1:].rename_axis(None, axis=1)
#set index by first column
df = df.set_index(df.columns[0])
print (df)
345 456 789
123
987 876 765 543
numpy
进行索引:arr = df.values
df = pd.DataFrame(arr[1:,1:], index=arr[1:,0], columns=arr[0,1:])
df.index.name = arr[0,0]
print (df)
345 456 789
123
987 876 765 543
创建数据框架时似乎出现了问题。数据框架是如何创建的?您很可能可以通过正确的创建来解决问题。
如果这不是一个选项,请尝试以下操作:
pandas.DataFrame.reset_index()
是您想要的。至于列名,只需使用 pandas.DataFrame.append()
将它们作为常规行添加,并使用 df.columns
作为参数(其中 df
是您的数据框架),然后重命名列。
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}) # Sample DataFrame
new_row = {'A': 7, 'B': 8} # Create a new row as a dictionary
df.loc[-1] = new_row # Append row to the bottom with index=-1
df.index = df.index + 1 # Shift df index by 1 to maintain index continuity
df.sort_index(inplace=True) # Sort by index to ensure the new row at the top
pd.read_csv(..., header=None)
时,应该解决这个问题。 话虽如此,重置index
很容易df.reset_index()
。 列有点烦人df.T.reset_index().T
。 但是如果你真的需要两者,那么你需要解决结果的第一个位置放什么值的问题。 意思是,数据框左上角将没有值。 我认为你需要一个 [mcve]。 - piRSquared