我試圖通過將第二個df的第一行加入第一個df的第一行來合并兩個資料框架。我還試著將它們連接起來,但也失敗了。 資料的格式是
1,3, N0128,Durchm, 5.0,0.1,5.0760000000000005,0.076,-----****--
2,0.000,,,,,,,
3,3,N0129,位置,62. 2,0.376,62.238,0.136,***----
4,76.1,-36.000, 0.300,-36.057,,,,
5,2,N0130,Durchm, 5.0,0.1,5.067,0.067,-----***----。
6,0.000,,,,,,,
輸出的預期格式應該是
1,3, N0128,Durchm, 5.0,0.1,5.076000000005,0.076,-----****--, 0.000,,,,,,,
2,3,N0129,位置,62.2,0.376, 62. 238,0.136,***--**,76.1, -36. 000,0.300,-36.057,,,,
3,N0130,Durchm, 5.0,0.1,5.067,0.067,-----**--,0.000,,,,,,,
我已經將上面的資料框架分割成兩個框架。第一個框架只包含奇數的索引,第二個框架包含偶數的索引。 我現在的問題是,通過將第二個資料框架的第一行添加到第一個資料框架的第一行來合并/銜接這兩個框架。我已經嘗試了一些合并/銜接的方法,但都失敗了。所有的列印函式都不是必要的,我只是用它們來在控制臺中快速瀏覽。 我覺得最舒服的代碼是:
os.chdir(output)
csv_files = os.listdir('. ')
for csv_file in(csv_files)。
if csv_file.endswith(".asc.csv")。
df = pd.read_csv(csv_file)
keep_col = ['Messpunkt'/span>, 'Zeichnungspunkt'/span>, 'Eigenschaft'/span>, 'Position'/span>, 'Sollmass','Toleranz', 'Abweichung', 'Lage']
new_df = df[keep_col]
new_df = new_df[~new_df['Messpunkt'].isin(['**Teil']) ]
new_df = new_df[~new_df['Messpunkt'].isin(['**KS-Oben']) ]
new_df = new_df[~new_df['Messpunkt'].isin(['**KS-Unten']) ]
new_df = new_df[~new_df['Messpunkt'].isin(['**N']) ]
print(new_df)
new_df.to_csv(output csv_file)
df1 = new_df[new_df.index % 2 ==1]
df2 = new_df[new_df.index % 2 ==0]
df1.reset_index()
df2.reset_index()
print (df1)
print (df2)
merge_df = pd.concat([df1,df2], axis=1)
print (merge_df)
merge_df.to_csv(output csv_file)
我非常希望得到一些幫助。
使用這段代碼,輸出結果是:
1,3, N0128,Durchm, 5.0,0.1,5.0760000000000005,0.076,-----****--,,,,,,,,
2,,,,,,,,,0.000,,,,,,,
3,3,N0129,位置,62. 2,0.376,62.238,0.136, ***--,,,,,,,,
4,,,,,,,,,76.1,-36.000, 0.300,-36.057,,,,
5,2,N0130,Durchm, 5.0,0.1,5.067,0.067,-----***--,,,,,,,,
6,,,,,,,,,0.000,,,,,,,
uj5u.com熱心網友回復:
當我使用reset_index()在兩個DataFrames中擁有相同的索引時,我得到了預期的結果。
它可能還需要drop=True來跳過索引作為新的列
pd.concat([df1.reset_index(drop=True), df2.reset_index(drop=True)], axis=1)
最小的作業實體。
我只用io來模擬記憶體中的檔案。
text = ''1,3,N0128,Durchm.,5.0,0.1,5.076000000005,0.076,-----_01--
2,0.000,,,,,,,
3,3,N0129,Position,62.2,0.376,62.238,0.136,***---
4,76.1,-36.000,0.300,-36.057,,,,
5,2,N0130,Durchm.,5.0,0.1,5.067,0.067,-----***---
6,0.000,,,,,,,''/span>
import pandas as pd
import io
pd.options.display.max_columns = 20 # 以顯示所有列。
df = pd.read_csv(io.StringIO(text), header=None, index_col=0)
#print(df)
df1 = df[df.index % 2 == 1] # .reset_index(drop=True)]
df2 = df[df.index % 2 == 0] # .reset_index(drop=True)]
#print(df1)/span>
#print(df2)。
merge_df = pd.concat([df1.reset_index(drop=True), df2.reset_index(drop=True)], axis=1)
print(merge_df)
結果:
1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8
0 3.0 N0128 Durchm. 5.0 0.100 5.076 0.076 -----****-- 0.0 NaN NaN NaN NN NaN
1 3.0 N0129 位置 62.2 0.376 62. 238 0.136 ***-- 76.1 -36. 000 0.300 -36.057 NaN NaN NaN
2 2.0 N0130 Durchm. 5.0 0.100 5. 067 0.067 -----***--- 0.0 NaN NaN NaN NaN NaN NaN
編輯:
它可能需要
merge_df.index = merge_df.index 1
以糾正索引。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/326399.html
標籤:
上一篇:按行轉換為特定值后的NA
