查找行值并替换 Python 中的列名
Lookup row values and replace column names in Python
我有两个CSV文件,结构如下图(转换成excel)
和
我想从第一个文件的“TAG”列中获取值并在第二个文件中查找 headers。
首先,想检查TAG列中的所有值是否都可以匹配到第二个文件中的列header,并得到那些不能匹配的值的列表与列 header.
匹配
其次,在值可以与 headers 匹配的地方,将 headers 替换为第一个文件中“Short”列中的值。
在 Python 中执行此操作的最简单方法是什么?
import pandas as pd
# Read the first CSV file with Pandas
df1 = pd.read_csv('first_file.csv')
rename_dict = {row.TAG: row.SHORT for row in df1.itertuples()}
# Read the second CSV file in Python with pandas
df2 = pd.read_csv('sec_file.csv')
# Get a list with all matched TAG values in header names
matched = [tag for tag in df1.loc[:, 'TAG'] if tag in df2.columns]
# Replace the header names from TAG with SHORT and overwrite the second file
df2.rename(columns=rename_dict, inplace=True)
df2.to_csv('sec_file.csv')
我有两个CSV文件,结构如下图(转换成excel)
和
我想从第一个文件的“TAG”列中获取值并在第二个文件中查找 headers。
首先,想检查TAG列中的所有值是否都可以匹配到第二个文件中的列header,并得到那些不能匹配的值的列表与列 header.
匹配其次,在值可以与 headers 匹配的地方,将 headers 替换为第一个文件中“Short”列中的值。
在 Python 中执行此操作的最简单方法是什么?
import pandas as pd
# Read the first CSV file with Pandas
df1 = pd.read_csv('first_file.csv')
rename_dict = {row.TAG: row.SHORT for row in df1.itertuples()}
# Read the second CSV file in Python with pandas
df2 = pd.read_csv('sec_file.csv')
# Get a list with all matched TAG values in header names
matched = [tag for tag in df1.loc[:, 'TAG'] if tag in df2.columns]
# Replace the header names from TAG with SHORT and overwrite the second file
df2.rename(columns=rename_dict, inplace=True)
df2.to_csv('sec_file.csv')