如何更改包含Small_X,Large_X(其中X为数字1,2,3,...等)的列,并将所有其他值传播到新记录,并新建一个名为“ New_Column”的列”将表示X值。
import pandas as pd
data = {'Time': ['12/1/19 0:00', '12/1/19 0:05'],
'Small_1': [1, 0],
'Large_1': [0, 0],
'Con_1': [0, 0],
'Small_2': [0, 0],
'Large_2': [0, 0],
'Con_2': [0, 0],
'Small_10': [1, 0],
'large_10': [0, 0],
'Con_10': [0, 0],
'Some_other_value': [78, 96],
}
df = pd.DataFrame(data)
以上输入数据应使用熊猫格式为以下格式。
答案 0 :(得分:1)
我首先建议对感兴趣的filter
列,然后对melt
列,然后在“ _”上命名split
列,然后对数据帧进行pivot
:>
# Filter columns
df = df.filter(regex=r"^([Cc]on|[Ll]arge|[Ss]mall|Time).*")
# Melt dataframe
new = df.melt(id_vars="Time")
# Split column name
new[["variable", "New_Column"]] = new.variable.str.split("_", expand=True)
# Set variable as title
new["variable"] = new.variable.str.title()
# Pivot dataframe
new = pd.pivot_table(new, index=["Time", "New_Column"], values="value", columns="variable")
print(new.reset_index())
答案 1 :(得分:1)
替代代码:
下面的代码使用.stack()
,.unstack()
和.pivot_table()
。它仅选择性地选择在列表small
中指定的具有字符串large
,con
,key
的列名称进行拆分。
注意:
aggfunc=np.max
中的.pivot_table()
聚合。可以根据需要将其更改为任何其他类型的聚合方法,例如np.min
,np.sum
或自定义函数。Time
代码:
# Import libraries
import pandas as pd
# Create DataFrame (copy pasted from question above)
data = {'Time': ['12/1/19 0:00', '12/1/19 0:05'],
'Small_1': [1, 0],
'Large_1': [0, 0],
'Con_1': [0, 0],
'Small_2': [0, 0],
'Large_2': [0, 0],
'Con_2': [0, 0],
'Small_10': [1, 0],
'large_10': [0, 0],
'Con_10': [0, 0],
'Some_other_value': [78, 96],
}
df = pd.DataFrame(data)
# Set Time as index
df = df.set_index('Time')
# Rename columns
df.columns = df.columns.str.lower() # change case to lower
# Stack
df = df.stack().reset_index() # convert columns to rows
# Split based on condition
key = ['small', 'large','con'] # Column names to be split
df['col1'] = df['level_1'].apply(lambda x: x.split('_')[0] if x.split('_')[0] in key else x)
df['New_Column'] = df['level_1'].apply(lambda x: x.split('_')[1] if x.split('_')[0] in key else np.NaN)
# Drop/rename columns
df = df.drop(['level_1'], axis=1)
df.columns.name=''
# Pivot using aggregate function: np.max
df = df.pivot_table(index=['Time', 'New_Column'], columns='col1', values=0, aggfunc=np.max)
# Rearrange
df = df.reset_index()
df.columns.name=''
df = df[['Time','small', 'large', 'con', 'New_Column']]
输出
print(df)
Time small large con New_Column
0 12/1/19 0:00 1 0 0 1
1 12/1/19 0:00 1 0 0 10
2 12/1/19 0:00 0 0 0 2
3 12/1/19 0:05 0 0 0 1
4 12/1/19 0:05 0 0 0 10
5 12/1/19 0:05 0 0 0 2