有没有一种方法可以在给定行索引的情况下组合Pandas DataFrame中的行



我希望将第2行与第0行合并,使行的单位成为列标题的一部分,而不是跟随数据点。数据来自这种格式的.csv文件,但如果单位在标题中,处理起来会容易得多。该单元并不总是";mi/h";并且可以在任何给定的参考文件中改变。像这样的部分是从包含许多不同格式表的较大.csv文件中提取的。我的最终目标是将每个部分单独导出到自己的.csv文件中。这已经起作用了,但我希望如上所述调整数据,然后继续将其导出到自己的.csv文件中。

0 Avg Wind Speed       Gust Speed           Min Wind Speed     
1                 5.26                10.74                 1.34
2                 mi/h                 mi/h                 mi/h

理想情况下,输出应该是这样的:

0 Avg Wind Speed (mi/h)       Gust Speed (mi/h)           Min Wind Speed (mi/h)     
1                 5.26                10.74                 1.34

从第0行和第2行创建df标头

import pandas as pd
# given your sample data
data = {0: ['Avg Wind Speed', '5.26', 'mi/h'], 
1: ['Gust Speed', '10.74', 'mi/h'],
2: ['Min Wind Speed', '1.34', 'mi/h']}
df = pd.DataFrame(data)
0           1               2
0  Avg Wind Speed  Gust Speed  Min Wind Speed
1            5.26       10.74            1.34
2            mi/h        mi/h            mi/h
# create the new header from row 0 and 2
header = (df.iloc[0, :] + ' ('+ df.iloc[2, :] + ')').to_list()
# if there can be whitespace or floats, use the following line for header
header = (df.iloc[0, :].astype(str).str.strip() + ' ('+ df.iloc[2, :].astype(str).str.strip() + ')').to_list()
['Avg Wind Speed (mi/h)', 'Gust Speed (mi/h)', 'Min Wind Speed (mi/h)']
# set as header
df.columns = header
# delete row 0 and 2
df = df.drop(labels=[0, 2])
# final df
Avg Wind Speed (mi/h) Gust Speed (mi/h) Min Wind Speed (mi/h)
1                  5.26             10.74                  1.34

写入新行0

# overwrite row 0
df.iloc[0] = header
# delete row 2
df = df.drop(labels=[2])
# final df
0                  1                      2
0  Avg Wind Speed (mi/h)  Gust Speed (mi/h)  Min Wind Speed (mi/h)
1                   5.26              10.74                   1.34

如果正在更新标头而不是第0行和第2行

data = {'Avg Wind Speed': ['5.26', 'mi/h'],
'Gust Speed': ['10.74', 'mi/h'],
'Min Wind Speed': ['1.34', 'mi/h']}
df = pd.DataFrame(data)
Avg Wind Speed Gust Speed Min Wind Speed
0           5.26      10.74           1.34
1           mi/h       mi/h           mi/h
# get values from row 1
row1 = df.iloc[1].tolist()
# update the column headers
df.columns = [f'{c} ({row1[i]})' for i, c in enumerate(df.columns)]
# drop row 1
df = df.drop(labels=[1])
# final df
Avg Wind Speed (mi/h) Gust Speed (mi/h) Min Wind Speed (mi/h)
0                  5.26             10.74                  1.34
df.columns=[c+"("+str(df.loc[2,c])+")" for c in df.columns]

通过添加第二行和相应列的值(转换为字符串(来重命名所有列。

df.loc[0,:]=[str(df.loc[0,c])+str(df.loc[2,c]) for c in df.columns ]

此解决方案编辑第一行而不是列,不确定要编辑哪一行。

相关内容

最新更新