E.K*_*.K. 82 python rename dataframe pandas
我必须处理的数据有点乱.它的数据中包含头名.如何从现有的pandas数据框中选择一行并将其(重命名为)列标题?
我想做的事情如下:
header = df[df['old_header_name1'] == 'new_header_name1']
df.columns = header
Run Code Online (Sandbox Code Playgroud)
unu*_*tbu 154
In [21]: df = pd.DataFrame([(1,2,3), ('foo','bar','baz'), (4,5,6)])
In [22]: df
Out[22]:
0 1 2
0 1 2 3
1 foo bar baz
2 4 5 6
Run Code Online (Sandbox Code Playgroud)
将列标签设置为等于第2行(索引位置1)中的值:
In [23]: df.columns = df.iloc[1]
Run Code Online (Sandbox Code Playgroud)
放下第二行:
In [24]: df.drop(df.index[1])
Out[24]:
1 foo bar baz
0 1 2 3
2 4 5 6
Run Code Online (Sandbox Code Playgroud)
小智 41
这是有效的(pandas v'0.19.2'):
df.rename(columns=df.iloc[0])
Run Code Online (Sandbox Code Playgroud)
sha*_*r_m 23
重新创建数据框会更容易。这也将从头开始解释列类型。
headers = df.iloc[0]
new_df = pd.DataFrame(df.values[1:], columns=headers)
Run Code Online (Sandbox Code Playgroud)
Gov*_*nda 17
要重命名标头而不重新分配 df:
df.rename(columns=df.iloc[0], inplace = True)
Run Code Online (Sandbox Code Playgroud)
要删除该行而不重新分配 df:
df.drop(df.index[0], inplace = True)
Run Code Online (Sandbox Code Playgroud)
您可以通过表示.csv的参数在read_csv或read_html构造函数中指定行索引。这样做的好处是可以自动删除所有前面应该是垃圾的行。headerRow number(s) to use as the column names, and the start of the data
import pandas as pd
from io import StringIO
In[1]
csv = '''junk1, junk2, junk3, junk4, junk5
junk1, junk2, junk3, junk4, junk5
pears, apples, lemons, plums, other
40, 50, 61, 72, 85
'''
df = pd.read_csv(StringIO(csv), header=2)
print(df)
Out[1]
pears apples lemons plums other
0 40 50 61 72 85
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
145795 次 |
| 最近记录: |